当前位置:主页 > vue > vue组件间传值

vue组件间传值

xi6年前 (2019-11-14)vue9980

父传子

利用props传值,子组件中规定props数据类型,然后父组件使用子组件时需要绑定数据在子组件上:
父组件:

<template>
  <div class="parents-div">
    <!--绑定msg传入子组件-->
    <Children :msg='msg'/>
  </div>
</template>

<script>
import Children from './Children.vue'//引入子组件
export default {
  components:{Children},//注册子组件
  data(){
    return{
      msg:"test",//父组件需要传递的数据
    }
  },
}
</script>
<style scoped>
.parents-div{}
</style>

子组件:

<template>
  <div class="children-div">
    <!--页面中使用数据-->
    {{msg}}
  </div>
</template>

<script>
export default {
  props:{
    msg:String,//子组件需要接受的数据
  },
  components:{},
}
</script>
<style scoped>
.children-div{}
</style>

子传父

利用$emit传值,父组件监听自定义事件,在子组件中通过触发该事件来传值:

子组件:

<template>
  <div class="children-div"></div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      msg: "test", //子组件需要传递给父组件的数据
    };
  },
  mounted() {
    this.getMsg();
  },
  methods: {
    getMsg() {
      this.$emit("get-msg", this.msg);
    },
  },
};
</script>
<style scoped>
.children-div {
}
</style>

父组件:

<template>
  <div class="parents-div">
    <!--触发自定义事件get-msg接收子组件数据-->
    <Children @get-msg="getMsg" />
  </div>
</template>

<script>
import Children from "./Children.vue"; //引入子组件
export default {
  components: { Children }, //注册子组件
  methods: {
    //获取到子组件传递过来的数据
    getMsg(msg) {
      console.log(msg);
    },
  },
};
</script>
<style scoped>
.parents-div {
}
</style>

vuex传值

vuex相当于一个公共仓库,保存着所有组件都能共用的数据,需要时可以直接使用,不需要考虑组件间是否有引用与被引用的父子关系。

转载请标注来源与原作者

本文链接:http://xiblogs.top/?id=22

返回列表

上一篇:vue中使用sass

下一篇:vuex的使用

“vue组件间传值” 的相关文章

vue动态绑定样式

vue动态绑定样式

每次点击方块时通过三元表达式,改变对应的class,每一个不同的class对应不同的样式,从而通过改变class实现样式的切换。 <template> <div class=...

vscode使用vue代码模板

vscode使用vue代码模板

1、vscode中打开:文件>首选项>用户片段>输入vue按下回车2、复制下面代码并保存。 { "Print to console": {...

vue+xlsx实现表格的导入导出

vue+xlsx实现表格的导入导出

前言前端在开发过程中若是管理系统之类的业务系统,则大多都会涉及到表格的处理,其中最为常见的就是表格的导入导出。有很多办法都可以实现,其中最简单的还是使用插件xlsx。 实现目标1、对表格数据进行增加...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。