[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-vuevue3中子元件傳資料給父元件的作法":3},{"id":4,"slug":5,"title":6,"description":7,"content":8,"date":9,"image":10,"imageAlt":6,"author":11,"categories":14,"path":19,"minRead":20},153,"vuevue3中子元件傳資料給父元件的作法","[Vue]Vue3中子元件傳資料給父元件的作法","Vue3中子元件傳資料給父元件的作法 隨著使用Vue越來越深入，一定會遇到父子元件傳資料的需求，我想有稍微研究 […]","\u003Ch1>Vue3中子元件傳資料給父元件的作法\u003C\u002Fh1>\n\u003Cp>隨著使用Vue越來越深入，一定會遇到父子元件傳資料的需求，我想有稍微研究過一定知道這個口訣「Props in, Event out」XD，父傳子用props，子傳父用event。那今天就來記錄我實作時遇到的狀況。\u003C\u002Fp>\n\u003Cp>在運作上，子元件透過觸發「事件event」的作法來更新父元件的資料，Vue3中使用了\u003Cstrong>v-on\u003C\u002Fstrong>來實作，父元件需要有個監聽事件如下：\u003C\u002Fp>\n\u003Ch1>parent-component.js\u003C\u002Fh1>\n\u003Cpre>\u003Ccode>&lt;child-component\n    @listenevent=&quot;updateEvent&quot;\n>&lt;\u002Fchild-component&gt;\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cpre>\u003Ccode>&lt;script&gt;\nexport default defineComponent({\n   setup() {\n\n    },\n  methods: {\n    updateEvent(val) {\n      \u002F\u002F這邊會被觸發\n      \u002F\u002F做你想做的事\n      console.log(val)\n    }\n  }\n});\n&lt;\u002Fscript&gt;\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>先準備一個listenevent監聽事件，取名為updateEvent，當子元件打資料過來時會觸發updateEvent。\u003C\u002Fp>\n\u003Ch3>child-component.js\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>&lt;script&gt;\nexport default defineComponent({\n   setup(_,{ emit }) {\n    const handleChange = (value) =&gt; {\n        emit(&quot;listenevent&quot;,value)\n    }\n    onMounted(() =&gt; {\n      handleChange(&quot;hello&quot;)\n      });\n    },\n});\n&lt;\u002Fscript&gt;\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cp>接著在子元件增加觸發\u003Cstrong>listenevent\u003C\u002Fstrong>事件的方式，如上\u003Cstrong>handleChange\u003C\u002Fstrong>，範例是onMounted時會觸發\u003Cstrong>handleChange\u003C\u002Fstrong>，這時會打&quot;hello&quot;回到父元件，這時父元件的\u003Cstrong>updateEvent\u003C\u002Fstrong>就會被觸發，應該就能看到&quot;hello&quot;囉。\u003C\u002Fp>\n\u003Cp>如果出現「...vue 3 emit warning &quot; Extraneous non-emits event listeners&quot;...」的警告提示，記得子元件要加上emits的宣告。\u003C\u002Fp>\n\u003Ch3>child-component.js\u003C\u002Fh3>\n\u003Cpre>\u003Ccode>&lt;script&gt;\nexport default defineComponent({\n   emits: [&quot;getGameitle&quot;], \u002F\u002F&lt;---加上宣告\n   setup(_,{ emit }) {\n    const handleChange = (value) =&gt; {\n        emit(&quot;listenevent&quot;,value)\n    }\n    onMounted(() =&gt; {\n      handleChange(&quot;hello&quot;)\n      });\n    },\n});\n&lt;\u002Fscript&gt;\u003C\u002Fcode>\u003C\u002Fpre>\n","2022-11-14T20:00:08","\u002Fapi\u002Fproxy-image?url=https%3A%2F%2Fpost.billxu.net%2Fwp-content%2Fuploads%2F2022%2F11%2F256px-Vue.js_Logo_2.svg_.png",{"name":12,"link":13},"Chih Fan","http:\u002F\u002Fpost.billxu.net",[15,17],{"name":16,"slug":16},"frontend",{"name":18,"slug":18},"vue","\u002Fblog\u002Fvuevue3中子元件傳資料給父元件的作法",1]