vue 函数式组件如何添加监听watch
我有这样一段代码,动态生成组件,
Vue.component("ht-vnode", { functional: true,
render: (h, ctx) => {
// 复制父组件的属性到子组件中
let assembly = {
...ctx.props.vnode.componentOptions.propsData,
...ctx.props
};
delete assembly["vnode"];
ctx.props.vnode.componentOptions.propsData = assembly;
ctx.props.vnode.componentOptions.listeners = ctx.listeners;
// ctx.props.vnode.context.
console.log('ctx===', ctx)
return ctx.props.vnode;
}
});
};
然后在其它组件里面这样使用:
<ht-vnode :vnode="vnode" :label-width="labelWidth" @enter-search="search" @field-loaded="handleFieldLoaded" @input-change="handleInputChange" @change-options="handleOptionsChange"/>
现在的问题是我的ht-vnode组件里面有个props属性想监听它的变化,如何处理呢?
回答:
什么是函数式组件
没有管理任何状态,也没有监听任何传递给它的状态,也没有生命周期方法,它只是一个接受一些 prop 的函数。简单来说是 一个无状态和无实例的组件
回答:
那你就不应该用 Functional Components,它的定位就是非响应式的。
https://vuejs.org/v2/guide/re...
The anchored heading component we created earlier is relatively simple. It doesn’t manage any state, watch any state passed to it, and it has no lifecycle methods. Really, it’s only a function with some props.
In cases like this, we can mark components as functional, which means that they’re stateless (no reactive data) and instanceless (no this context).
【补充:评论区的示例代码】
const watchers = [];Vue.component('ht-vnode', {
props: {
vnode: Object
},
mounted() {
this.$nextTick(() => {
const handler = function (newVal, oldVal) {
console.log('BINGO! It changed!', newVal, oldVal);
}
const setWatchers = function (coms) {
if (!coms || !coms.length)
return;
// 递归设置子组件、子组件的子组件、子组件的子组件的子组件 ... 的 Watcher
for (let i = 0; i < coms.length; i++) {
let child = coms[i];
let watcher = child.$watch('$data', handler, { deep: true, immediate: true });
watchers.push(watcher);
setWatchers(child.$children);
}
}
setWatchers(this.$children);
});
},
beforeUnmount() {
// 卸载 Watcher
watchers.forEach(unwatch => unwatch());
},
render(h) {
// 省略跟 Watch 无关的代码
}
});
这样当你输入值就会触发 watchHandler 了。注意会有两个触发事件,一个是外层那个 Field 组件的选中状态改变;一个是里面那个 Input 组件输入值改变。
以上是 vue 函数式组件如何添加监听watch 的全部内容, 来源链接: utcz.com/p/936209.html