如何监听“道具"变化 [英] How to listen for 'props' changes
本文介绍了如何监听“道具"变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 VueJs 2.0 文档中,我找不到任何可以监听的钩子props
变化.
VueJs 有类似 onPropsUpdated()
或类似的钩子吗?
更新
正如@wostex 建议的那样,我试图watch
我的财产,但没有任何改变.然后我意识到我有一个特殊情况:
<child :my-prop="myProp"></child>模板><脚本>导出默认{道具:['myProp']}
我将父组件接收到的 myProp
传递给 child
组件.然后 watch: {myProp: ...}
不起作用.
解决方案
你可以watch
props 在 props 改变时执行一些代码:
new Vue({el: '#app',数据: {文字:'你好'},成分: {'孩子' : {模板:`<p>{{ myprop }}</p>`,道具:['myprop'],手表: {myprop: function(newVal, oldVal) {//看它console.log('Prop 改变了:', newVal, ' | was: ', oldVal)}}}}});
<script src="https://unpkg.com/vue/dist/vue.js"></script><div id="应用程序"><child :myprop="text"></child><button @click="text = 'Another text'">更改文本</button>
In the VueJs 2.0 docs I can't find any hooks that would listen on props
changes.
Does VueJs have such hooks like onPropsUpdated()
or similar?
Update
As @wostex suggested, I tried to watch
my property but nothing changed. Then I realized that I've got a special case:
<template>
<child :my-prop="myProp"></child>
</template>
<script>
export default {
props: ['myProp']
}
</script>
I am passing myProp
that the parent component receives to the child
component. Then the watch: {myProp: ...}
is not working.
解决方案
You can watch
props to execute some code upon props changes:
new Vue({
el: '#app',
data: {
text: 'Hello'
},
components: {
'child' : {
template: `<p>{{ myprop }}</p>`,
props: ['myprop'],
watch: {
myprop: function(newVal, oldVal) { // watch it
console.log('Prop changed: ', newVal, ' | was: ', oldVal)
}
}
}
}
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<child :myprop="text"></child>
<button @click="text = 'Another text'">Change text</button>
</div>
这篇关于如何监听“道具"变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文