解决 Vue mounted 中无法获取 props 值

2023-02-10 10:55:46
# 解决 Vue mounted 中无法获取 props 值 ## 问题描述 父组件 `App` 向子组件 `MyComponent` 传值,子组件想在 `mounted` 中使用该值更新本组件的 `data`,发现无法接收到该值。 `@/App.vue` ```html <template> <div id="app"> <my-component :name="name" /> </div> </template> <script> import MyComponent from "@/components/MyComponent"; export default { name: "App", components: { MyComponent, }, data() { return { name: "", }; }, mounted() { this.name = "Patrick"; }, }; </script> <style> * { margin: 0; padding: 0; } #app { width: 100vw; height: 100vh; background-color: #eee; } </style> ``` `@/components/MyComponent.vue` ```html <template> <div class="my-component">你好,我叫:{{ text }}</div> </template> <script> export default { name: "MyComponent", props: ["name"], data() { return { text: "", }; }, mounted() { this.text = this.name; }, }; </script> <style> .my-component { padding-top: 100px; text-align: center; } </style> ``` 运行结果: ![202302091628 解决 Vue mounted 中无法获取 props 值 00.png](https://static.daimaku.net/post/202302/10/05f3b05d1878a3410a60f1ed9c6029db.png) 在子组件的 `mounted()` 中,无法访问到父组件传递过来的 `name`。 ## 解决方案 解决方案是在子组件使用 `watch` 监听 `name` 的变化。下面修改 `@/components/MyComponent.vue`,删除 `mounted`,加入 `watch`。 ```html <template> <div class="my-component">你好,我叫:{{ text }}</div> </template> <script> export default { name: "MyComponent", props: ["name"], data() { return { text: "", }; }, watch: { name: function (value) { this.text = value; }, }, }; </script> <style> .my-component { padding-top: 100px; text-align: center; } </style> ``` ![202302091628 解决 Vue mounted 中无法获取 props 值 01.png](https://static.daimaku.net/post/202302/10/8f4b1009d37e48fe73937375e67d8f1b.png) ## 参考资料 - [props 和 mounted](https://www.cnblogs.com/ljwsyt/p/10594923.html)