9、基础语法知识点补充
使用ref获取dom节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello vue</title>
<!-- 引入Vue库 -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
mounted(){
// 打印 DOM
console.log(this.$refs.hello);
// 操作 DOM
this.$refs.hello.innerHTML = "<button>哈哈哈</button>"
},
template: `
<div>
<div ref="hello">
hello world!
</div>
</div>
`
});
const vm = app.mount('#root');
</script>
</html>
运行结果
使用ref获取子组件的引用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello vue</title>
<!-- 引入Vue库 -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
mounted(){
// 打印 子组件
console.log(this.$refs.hello);
// 调用子组件的方法
this.$refs.hello.print();
},
template: `
<div>
<common-item ref="hello" />
</div>
`
});
app.component('common-item', {
methods:{
print(){
console.log("子组件的打印方法!");
}
},
template: `
<div>hello world!</div>
`
});
const vm = app.mount('#root');
</script>
</html>
运行结果
provide和inject
用于数据在多层组件中传递
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello vue</title>
<!-- 引入Vue库 -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
provide: {
message: "Hello World!"
},
template: `
<div>
<common-item />
</div>
`
});
app.component('common-item', {
template: `
<child />
`
});
app.component('child', {
template: `
<child-child />
`
});
app.component('child-child', {
inject: ['message'],
template: `
<div>{{message}}</div>
`
});
const vm = app.mount('#root');
</script>
</html>
运行结果
provide里面的数据是data里面的数据
provide提供数据是一次性的,不是双向绑定的(不是动态变化的)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello vue</title>
<!-- 引入Vue库 -->
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data(){
return{
message: 'Hello World!'
}
},
provide(){
return{
message: this.message
}
},
template: `
<div>
<common-item />
</div>
`
});
app.component('common-item', {
template: `
<child />
`
});
app.component('child', {
template: `
<child-child />
`
});
app.component('child-child', {
inject: ['message'],
template: `
<div>{{message}}</div>
`
});
const vm = app.mount('#root');
</script>
</html>