如何双向绑定props
?
- 传统方法
//父组件
<template>
<div id="app">
<HelloWorld :count1="count1" :changeCount1="changeCount1"/>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
import { ref } from "@vue/composition-api";
export default {
name: "App",
setup() {
const count1 = ref(0);
const changeCount1 = newCount1 => (count1.value = newCount1);
return {
count1,
changeCount1,
};
},
components: {
HelloWorld
}
};
</script>
//子组件
<template>
<div class="hello">
count2: {{count2}}
<button @click="onclick">change count2</button>
</div>
</template>
<script>
import { ref, watch } from "@vue/composition-api";
export default {
name: "HelloWorld",
props: ["count1", "changeCount1"],
setup(props) {
const count2 = ref(0);
const onclick = () => {
count2.value++;
};
watch(() => props.count1, (count1, prevCount1) => {
count2.value = props.count1;
});
watch(() => {
props.changeCount1(count2.value);
});
return {
count2,
onclick
};
}
};
</script>
-
.sync
绑定props
//父组件
<template>
<div id="app">
<HelloWorld :count3.sync="count1"/>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
import { ref } from "@vue/composition-api";
export default {
name: "App",
setup() {
const count1 = ref(0);
const changeCount1 = newCount1 => (count1.value = newCount1);
return {
count1,
changeCount1,
};
},
components: {
HelloWorld
}
};
</script>
//子组件
<template>
<div class="hello">
count3: {{count3}}
<button @click="click1">change count3</button>
</div>
</template>
<script>
import { ref, watch } from "@vue/composition-api";
export default {
name: "HelloWorld",
props: ["count3"],
setup(props, context) {
const click1 = () => {
const newCount3 = props.count3 + 1;
context.emit("update:count3", newCount3);
};
return {
click1
};
}
};
</script>
其中,<HelloWorld :count3.sync="count1"/>
相当于
<HelloWorld :count3="count1" @update:count3="count1=$event"/>
的缩写,参见官方文档
watch如何监听多个sources?
- 对于ref,可使用:
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
/* ... */
})
- 对于props、state,可使用:
watch([() => props.count1, () => props.count2], ([count1, count2], [prevCount1, prevCount2]) => {
/* ... */
});
网友评论