眾所周知,vue是單向資料流,子元件不能直接改變父元件中的變量,如下:
#parent.vue
<template> <p> <p>parent:{{ msg }}</p> <children :msg="msg"></children> </p> </template> <script> import children from '@/components/children' export default { name: 'parent', data() { return { msg: 'from parent' } }, components: { children } } </script>
children.vue
<template> <p> <p>children:{{ msg }}</p> <p> <button @click='changeChild'>点击改变children的msg</button> </p> </p> </template> <script> export default { name: 'children', data () { return { } }, props: ['msg'], methods: { changeChild() { this.msg = 'from children' } } } </script>
頁面如下:
##點擊後:
this.$emit()這個函數了。
第一種:v-model傳遞
#父元件修改:##<template>
<p>
<p>parent:{{ msg }}</p>
<children v-model="msg"></children>
</p>
</template>
<script>
export default {
name: 'children',
data () {
return {
}
},
model: {
prop: "msg"
},
props: ['msg'],
methods: {
changeChild() {
this.$emit('input', "child")
}
}
}
</script>
#可見父子元件的值同步了
第二種:明確指定回應事件(@)
父元件修改:<template>
<p>
<p>parent:{{ msg }}</p>
<children @upChange="changeMsg" :msg="msg"></children>
</p>
</template>
<script>
import children from '@/components/children'
export default {
name: 'parent',
data() {
return {
msg: 'from parent'
}
},
components: {
children
},
methods: {
changeMsg() {
this.msg = "收到子组件信号,嘤嘤嘤"
}
}
}
</script>
<script> export default { name: 'children', data () { return { } }, model: { prop: "msg" }, props: ['msg'], methods: { changeChild() { this.$emit('upChange', "给你一个value") this.msg = 'from children' } } } </script>
頁如下:
點擊後:
兩種方法都基本上可以達到預期效果,具體自己分情況使用
下面還是給個小範例:
#父元件:
##<template>
<p>
<children @upChange="changeMsg" :msg="msg"></children>
<children2 :msg2="msg2"></children2>
</p>
</template>
<script>
import children from '@/components/children'
import children2 from '@/components/children2'
export default {
name: 'parent',
data() {
return {
msg: 'from parent',
msg2: 'from parent'
}
},
components: {
children,
children2
},
methods: {
changeMsg(value) {
this.msg = value
this.changeChild2()
},
changeChild2() {
this.msg2 = "children2收到 children2收到 over over!"
}
}
}
</script>
<template> <p> <p>children:{{ msg }}</p> <p> <button @click='changeChild'>点击呼叫children2</button> </p> </p> </template> <script> export default { name: 'children', data () { return { } }, model: { prop: "msg" }, props: ['msg'], methods: { changeChild() { this.$emit('upChange', "children2,children2,收到请回答,收到请回答") } } } </script>
子元件二:
<template> <p> <p>children2: {{ msg2 }}</p> </p> </template> <script> export default { name: 'children2', data () { return { } }, props: ['msg2'] } </script>
頁如下: 點擊後:
本文介紹了vue資料綁定方式詳解,更多相關內容請關注php中文網。
相關推薦:
#
以上是vue資料綁定方式詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!