vue3.0中,添加了provide,inject语法,能实现多级组件之间的通信传值。示例代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>lesson 41</title>
<script src="https://unpkg.com/vue@next"></script>
<style>
</style>
</head>
<body>
<div id="root"></div>
</body>
<script>
//provide inject
const app = Vue.createApp({
setup() {
//引入方法
//readonly是只读属性,设置的值不可修改
const { provide, ref, readonly } = Vue;
const name = ref('dell');
//将name传递出去,传递出去的值不可在其他组件被修改
provide ('name', readonly(name));
//将changName方法传递出去,name值只能通过调用该组件中的方法来修改
provide('changName', (value) => {
name.value = value;
})
return { }
},
template:
`<div>
<child />
</div>
`,
});
app.component('child', {
setup() {
//引入方法
const { inject } = Vue;
//接受值
const name = inject('name');
//接受方法
const changName = inject('changName');
const handleClick = () => {
changName('lee');
}
return { name, handleClick }
},
template:'<div @click="handleClick">child--{{name}}</div>'
})
const vm = app.mount('#root');
</script>
</html>
ref获取dom元素节点
//dom ref
//CompositionAPI 的语法下,获取真实的 DOM 元素节点
const app = Vue.createApp({
setup() {
const { ref, onMounted } = Vue;
const hello = ref(null);
onMounted(() => {
console.log(hello.value);
})
return { hello }
},
template:
`<div>
<div ref="hello">hello world</div>
</div>
`,
});
const vm = app.mount('#root');