记录vue3的v-model的实现方式
vue3还是有些不同的噢
<template>
<div>
<p>state: a: {{ state.a }}</p>
<p>state.a(toRef): a: {{ xxx }}</p>
<p>state.a(ref): a: {{ xxxx }}</p>
<button @click="update1">toRef更新a</button>
<button @click="update2">ref更新a</button>
<!-- v-model:xxxx指定双向绑定的变量,仍然还是之前那个语法糖 -->
<ChildCom v-model:xxxx="xxx" />
</div>
</template>
<script lang='ts'>
import { defineComponent, reactive, toRef, ref, h } from "vue";
export default defineComponent({
name: "9_toRef",
components: {
// 定义一个子组件
ChildCom: defineComponent({
props: {
xxxx: {
type: Number,
require: true,
},
},
data() {
return {
a: "it worked"
};
},
setup(props, context) {
const xv = ref(props.xxxx === undefined ? 0 : props.xxxx);
// v-model 在vue3的写法
const update = () => {
console.log('update:xxxx');
context.emit('update:xxxx', ++ xv.value);
};
return {xv, update}
},
// jsx 渲染这个组件
render() {
return h("div", [
h(
"button",
{
// 这里和vue2是不一样的
onClick: this.update
},
"子组件更新值"
),
h("h1", this.xv + "---" + this.a),
]);
},
}),
},
setup() {
const state = reactive({
a: 1,
});
// 修改toRef的值会同步更新state
const xxx = toRef(state, "a");
// 但是修改ref的值并不会同步更新state!
const xxxx = ref(state.a);
const update1 = () => {
xxx.value++;
};
const update2 = () => {
xxxx.value++;
};
return {
state,
update1,
update2,
xxx,
xxxx,
};
},
});
</script>
<style>
</style>
一切尽在代码中。
版权声明
本文章由作者“衡于墨”创作,转载请注明出处,未经允许禁止用于商业用途
发布时间:2021年02月19日 10:32:21
备案号:
闽ICP备19015193号-1
关闭特效
评论区#
还没有评论哦,期待您的评论!
引用发言