Vue3之组件间传值避坑指南
大约 2 分钟
组件间传值的两个坑
本文主要是讲解了组件传值过程中的两个容易犯的小错误
- 一、是父组件传递过来的值不能修改
- 二、是父组件使用“-”分隔符定义属性传递值到子组件,子组件接收时需要将属性名改为驼峰命名方式
坑一、父组件传递过来的值是只读的
<!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" />
<script src="https://unpkg.com/vue@next"></script>
<title>组件间传值</title>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
num: 0
};
},
template: `
<div>
<counter :count = "num"/>
</div>
`
});
// 错误示例 对父组件传递过来的值做操作时,发现操作无效,
app.component('counter',{
props: ['count'],
template: `<div @click="count+=1">{{count}}</div>`
});
// 正确示例 复制一份父组件传递过来的值,对我们自己的值进行操作:
app.component("counter", {
props: ["count"],
data() {
return {
mCount: this.count
};
},
template: `<div @click="mCount+=1">{{mCount}}</div>`
});
const vm = app.mount("#root");
</script>
</html>
坑二、子组件接收属性名应为驼峰命名
当我们定义一个单词名称比较长的属性,并且用“-”分隔符连接的时候,子组件无法接收到正确的值,显示NaN。
这个到坑也是
VUE
中的单向数据流的概念,即子组件可以使用父组件传递过来的数据,但是不能修改父组件传递过来的数据
<!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" />
<script src="https://unpkg.com/vue@next"></script>
<title>组件间传值</title>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
content: "hello world"
};
},
template: `
<div>
<test :content-helloworld = "content"/>
</div>
`
});
// 错误示例:无法接受父组件的参数传递,显示为 NaN
app.component("test", {
props: ["content-helloworld"],
template: `<div>{{content-helloworld}}</div>`
});
// 正确示例:正常显示父组件传递的参数
app.component("test", {
props: ["contentHelloworld"],
template: `<div>{{contentHelloworld}}</div>`
});
const vm = app.mount("#root");
</script>
</html>
当我们定义的属性值中有用“-”分隔符分隔时,我们在接收值的时候,需要将属性名改成驼峰命名的方式,如上面的例子中父组件使用
content-helloworld
传递值到子组件,那么子组件接收到时候应该将其改成驼峰命名方式:使用contentHelloworld
接收