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

vue组件间传值

xi6年前 (2019-11-14)vue10580

父传子

利用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://www.xiblogs.top/?id=22

返回列表

上一篇:vue中使用sass

下一篇:vuex的使用

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

vue中按需引入Element-ui

vue中按需引入Element-ui

安装1、安装element-ui:npm i element-ui -S。2、安装babel-plugin-component:npm install babel-plugin-component -...

vue打包后dist的使用

vue打包后dist的使用

发现问题vue项目完成打包出dist后准备打开index.html,发现居然页面是一片空白,f12一片报红。 分析问题经过多次网上查询后发现这是由于vue打包时,脚手架会帮你配置好大量参数,但其中路...

DataV兼容vue3的方法

DataV兼容vue3的方法

发现问题在使用vue开发大屏时,发现了一个很好用的可视化组件库DataV(http://datav.jiaminghi.com/ ),不是阿里那个DataV哈,用vue2开发时都一切顺利,直到有一天升...

发表评论

访客

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