我們透過一個計數器元件來示範這個坑,當想對父元件傳遞過來的值做操作時,發現操作無效,先看程式碼:
<!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 { num:0 } }, template: ` <div> <counter :count = "num"/> </div> ` }); // 定义一个test组件 app.component('counter',{ props: ['count'], template: `<div @click="count+=1">{{count}}</div>` }); const vm = app.mount('#root'); </script> </html>
在上面的程式碼中,我們定義了一個counter元件接收父元件的一個count值,當點擊這個顯示的值時,我們做加一操作。這時候我們執行程式碼會發現,我們的值不會完成加一操作,而是會報父元件傳遞過來的值是唯讀的:
##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.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 { num:0 } }, template: ` <div> <counter :count = "num"/> </div> ` }); // 定义一个test组件 app.component('counter',{ props: ['count'], data(){ return{ mCount:this.count } }, template: `<div @click="mCount+=1">{{mCount}}</div>` }); const vm = app.mount('#root'); </script> </html>
<!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> ` }); // 定义一个test组件 app.component('test',{ props: ['content-helloworld'], template: `<div>{{content-helloworld}}</div>` }); const vm = app.mount('#root'); </script> </html>
content-helloworld這個屬性在父元件和子元件之間傳值,按照我們的理解,應該是能傳遞成功的,但是顯示的結果卻不正確
content-helloworld傳遞值到子元件,那麼子元件接收到時候應該將其改成駝峰命名方式:使用
contentHelloworld接收
<!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> ` }); // 定义一个test组件 app.component('test',{ props: ['contentHelloworld'], template: `<div>{{contentHelloworld}}</div>` }); const vm = app.mount('#root'); </script> </html>
#
以上是Vue3組件間傳值避坑方法有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!