当前位置:
首页 >
Vue之组件之间的数据传递
发布时间:2023/12/19
57
豆豆
生活随笔
收集整理的这篇文章主要介绍了
Vue之组件之间的数据传递
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
Vue的组件作用域都是孤立的,不允许在子组件的模板内直接引用父组件的数据,必须使用特定的方法才能实现组件之间的数据传递。
下列为在vue-cli创建项目中的操作
一·父组件向子组件传递数据
在Vue中,用props向子组件传递数据。
子组件部分:1 <template> 2 <div class='header'>{{logo}}</div> 5 </template> 6 <script> 7 export default{ 8 name:"headerDiv", 9 data(){ 10 return { 11 ............ 12 } 13 }, 14 props:["logo"] 15 } 16 </script>
如果需要从父组件获取logo值,就需要使用props:['logo']
在props中添加了元素之后,就不需要在data中再添加变量了
父组件部分:
1 <template> 2 <div id='app'> 3 <HeaderDiv :logo="logoMsg"></HeaderDiv> 4 </div> 5 </template> 6 <script> 7 import HeaderDiv from './compontents/header' 8 9 export default{ 10 name:'app', 11 data(){ 12 return { 13 logoMsg:'VUE' 14 } 15 }, 16 components:{ 17 HeaderDiv 18 } 19 } 20 </script>二·子组件向父组件传递数据
子组件主要通过事件传递数据给父组件
子组件部分:
1 <template> 2 <div class='header'> 3 <input v-model="name" @change="getCh"> 4 </div> 5 </template> 6 <script> 7 export default { 8 name:'header', 9 data(){ 10 return { 11 name:'' 12 } 13 }, 14 methods:{ 15 getCh:function(){ 16 this.$emit('setCh',this.name) 17 } 18 } 19 } 20 </script>当name变化时,将name传给父组件,
在getCh中用$emit来遍历setCh事件,并返回this.name
setCh是一个自定义事件,this.name通过该事件传递给父组件
父组件部分:
<template><div id='app'><HeaderDiv @trans='getCh'></HeaderDiv><div>{{user}}</div></div> </template> <script>import HeaderDiv from './components/header'export default {name:'app',data(){return {name:''}},methods:{getCh(msg){this.name=msg}},components:{HeaderDiv}} </script>三·子组件互相传值
1.在main.js里全局定义eventBus
2.firstchild.vue
<template><div><button @click="btn">我是子组件一</button></div> </template> <style type="text/css"></style> <script type="text/javascript">export default{name:'Firstchild',methods:{btn(){console.log('start');eventBus.$emit('name','hello')}}} </script>3.secondchild.vue
<template><div><button @click="btn2">我是子组件二</button></div> </template> <style type="text/css"></style> <script type="text/javascript">export default{name:'Secondchild',methods:{btn2(){console.log('end');eventBus.$on('name',function(val){console.log('我是firstchild组件传过来的'+val)})}}} </script>运行结果
转载于:https://www.cnblogs.com/wdxue/p/7541672.html
总结
以上是生活随笔为你收集整理的Vue之组件之间的数据传递的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: HAProxy用法详解 全网最详细中文文
- 下一篇: vue设置多选框默认勾选_Angular