黑龙江住房建设部网站,北京商业网站建设,信用网站建设意义,wordpress 虚拟订阅插件组件间传值的两个坑
我们都知道父组件可以把值传递到自组件中#xff0c;但是有时候子组件需要修改这个父组件传递过来的这个值#xff0c;我们可以想象下能修改成功吗#xff1f;这是坑之一。我们在组件间传值的时候#xff0c;都是一个属性名对应一个值#xff0c;接收…组件间传值的两个坑
我们都知道父组件可以把值传递到自组件中但是有时候子组件需要修改这个父组件传递过来的这个值我们可以想象下能修改成功吗这是坑之一。我们在组件间传值的时候都是一个属性名对应一个值接收的时候也是用这个属性名接收那么每一个用户自定义的属性名都能被接收到吗这是坑之二本文就让我们一起来看下这两个坑吧。
实例填坑
坑一
1. 发现天坑 我们通过一个计数器组件来演示这个坑当想对父组件传递过来的值做操作时发现操作无效先看代码 !DOCTYPE html
html langen
headmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0script srchttps://unpkg.com/vuenext/scripttitle组件间传值/title
/head
bodydiv idroot/div
/body
scriptconst app Vue.createApp({data() {return {num:0}},template: divcounter :count num//div });// 定义一个test组件app.component(counter,{props: [count],template: div clickcount1{{count}}/div});const vm app.mount(#root);
/script
/html在上面的代码中我们定义了一个counter组件接收父组件的一个count值当点击这个显示的值时我们做加一操作。这时候我们运行代码会发现我们的值并不会完成加一操作而是会报父组件传递过来的值是只读的 2. 填坑时刻
那假如我们要完成这个加一的功能怎么办呢答案就是我们复制一份父组件传递过来的值对我们自己的值进行操作
!DOCTYPE html
html langen
headmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0script srchttps://unpkg.com/vuenext/scripttitle组件间传值/title
/head
bodydiv idroot/div
/body
scriptconst app Vue.createApp({data() {return {num:0}},template: divcounter :count num//div });// 定义一个test组件app.component(counter,{props: [count],data(){return{mCount:this.count}},template: div clickmCount1{{mCount}}/div});const vm app.mount(#root);
/script
/html这时候我们再运行代码就会发现我们可以做加一操作了
坑2:
1.发现天坑 当我们定义一个单词名称比较长的属性并且用“-”分隔符连接的时候子组件无法接收到正确的值显示NaN。代码如下 !DOCTYPE html
html langen
headmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0script srchttps://unpkg.com/vuenext/scripttitle组件间传值/title
/head
bodydiv idroot/div
/body
scriptconst app Vue.createApp({data() {return {content:hello world}},template: divtest :content-helloworld content//div });// 定义一个test组件app.component(test,{props: [content-helloworld],template: div{{content-helloworld}}/div});const vm app.mount(#root);
/script
/html在上面的代码中我们使用content-helloworld这个属性在父组件和子组件之间传值按照我们的理解应该是能传递成功的但是显示的结果却不正确 上面到坑也是VUE中的单向数据流的概念即子组件可以使用父组件传递过来的数据但是不能修改父组件传递过来的数据
2.填坑时刻 当我们定义的属性值中有用“-”分隔符分隔时我们在接收值的时候需要将属性名改成驼峰命名的方式如上面的例子中父组件使用content-helloworld传递值到子组件那么子组件接收到时候应该将其改成驼峰命名方式使用contentHelloworld接收 !DOCTYPE html
html langen
headmeta charsetUTF-8meta http-equivX-UA-Compatible contentIEedgemeta nameviewport contentwidthdevice-width, initial-scale1.0script srchttps://unpkg.com/vuenext/scripttitle组件间传值/title
/head
bodydiv idroot/div
/body
scriptconst app Vue.createApp({data() {return {content:hello world}},template: divtest :content-helloworld content//div });// 定义一个test组件app.component(test,{props: [contentHelloworld],template: div{{contentHelloworld}}/div});const vm app.mount(#root);
/script
/html这样值就能正确显示了
总结
本文主要是讲解了组件传值过程中的两个容易犯的小错误一是父组件传递过来的值不能修改二是父组件使用“-”分隔符定义属性传递值到子组件子组件接收时需要将属性名改为驼峰命名方式