vue 数据传递

1.父子组件件数据传递:props

组件实例的作用域是孤立的。这意味着不能 (也不应该) 在子组件的模板内直接引用父组件的数据。要让子组件使用父组件的数据,我们需要通过子组件的 props 选项。

子组件要显式地用 props 选项声明它期待获得的数据:

 
     
Vue.component( 'child', {
// 声明 props
props: [ 'message'],
// 就像 data 一样,prop 可以用在模板内
// 同样也可以在 vm 实例中像“this.message”这样使用
template: '<span>{{ message }}</span>'
})

然后我们可以这样向它传入一个普通字符串:

 
     
<child message="hello!"> </child>

结果:hello!; 

通过这个我们可以得出 组件是相互孤立,互不影响的。

export default {
name: 'Concat',
components: {
child: {
props: [ 'datas', 'title'],
template: '<div>{{msg}}<span>{{title}}</span></div>',
data () {
return {msg: JSON.stringify( this.datas) + 'zxvv'}
},
computed: {
}
}
},
data () {
return {
title: '标题',
datas: {
test1: 'aa',
test2: 'bb'
}
}
}
}
在HTML中:

<child :datas="datas" :title="title" ></child>
这样就可以去到父组件中的datas 和 title

prop 是单向绑定的:当父组件的属性变化时,将传导给子组件,但是不会反过来。这是为了防止子组件无意修改了父组件的状态——这会让应用的数据流难以理解。
另外,每次父组件更新时,子组件的所有 prop 都会更新为最新值。这意味着你不应该在子组件内部改变 prop。如果你这么做了,Vue 会在控制台给出警告。

2.子组件向父组件传递数据

export default {
name: 'Concat',
components: {
child: {
template: `<div><button @click="test">{{msg}}</button></div>`, // 绑定触发事件
methods: {
test () { // 触发事件,以及自定义方法
this.$emit( 'get-data', this.msg) // 这里的this指的是当前子组件
}
},
data () {
return {
msg: 'ces wom saf'
}
}
}
},
methods: {
getData (msg) {
console.log(msg)
this.datas = msg
}
},
data () {
return {
datas: ''
}
}
}
HTML中写法如下:
<child @get-data="getData" ></child>


猜你喜欢

转载自blog.csdn.net/u011649976/article/details/77317638
今日推荐