当前位置:Gxlcms > JavaScript > vue.js里如何做到父向子组件传参

vue.js里如何做到父向子组件传参

时间:2021-07-01 10:21:17 帮助过:13人阅读

这次给大家带来的是vue.js 里如何做到父向子组件传参,这篇文章就给大家好好分析一下。

1.新建componentA.vue组件,代码如下:

  1. const STORAGE_KEY = 'todos-vue.js'
  2. export default{
  3. fetch(){
  4. return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]')
  5. },
  6. save(items){
  7. window.localStorage.setItem(STORAGE_KEY,JSON.stringify(items));
  8. }
  9. }

App.vue代码如下:


  1. <template>
  2. <div id="app">
  3. <h1 v-text="title"></h1>
  4. <input v-model="newItem" v-on:keyup.enter="addNew"/>
  5. <ul>
  6. <li v-for="item in items" v-bind:class="{finished:item.isFinished}" v-on:click='toogleFinish(item)'>
  7. {{item.label}}
  8. </li>
  9. </ul>
  10. <!-- 使用组件,注意驼峰命名法转化成短线 -->
  11. <!-- 向自组件传数据 -->
  12. <Component-a msgfromfather='you die!'></Component-a>
  13. </div>
  14. </template>
  15. <script>
  16. import Store from './store'
  17. import ComponentA from './components/componentA' //该组件会被加载到该页面
  18. export default {
  19. name: 'app',
  20. data () {
  21. return {
  22. title: 'this is a todo list',
  23. items:Store.fetch(),
  24. newItem:''
  25. }
  26. },
  27. components:{ //注册组件
  28. ComponentA
  29. },
  30. watch:{
  31. items:{
  32. handler(items){ //经过变化的数组会作为第一个参数传入
  33. Store.save(items)
  34. },
  35. deep:true //深度复制
  36. }
  37. },
  38. methods:{
  39. toogleFinish(item){
  40. item.isFinished = !item.isFinished
  41. },
  42. addNew(){
  43. this.items.push({
  44. label:this.newItem,
  45. isFinished:false,
  46. })
  47. this.newItem = ''
  48. }
  49. }
  50. }
  51. </script>
  52. <style>
  53. #app {
  54. font-family: 'Avenir', Helvetica, Arial, sans-serif;
  55. -webkit-font-smoothing: antialiased;
  56. -moz-osx-font-smoothing: grayscale;
  57. text-align: center;
  58. color: #2c3e50;
  59. margin-top: 60px;
  60. }
  61. .finished{
  62. text-decoration: underline;
  63. }
  64. </style>

componentA.vue代码如下:


  1. <template>
  2. <div class="hello">
  3. <h1>{{msg}}</h1>
  4. <h2>{{msgfromfather}}</h2>
  5. <button v-on:click="onClickMe">Click!</button>
  6. </div>
  7. </template>
  8. <<script>
  9. export default {
  10. data(){
  11. return{
  12. msg:'Hello form component a'
  13. }
  14. },
  15. props:['msgfromfather'],//自组件接收数据
  16. methods:{
  17. onClickMe(){
  18. console.log(this.msgfromfather);
  19. }
  20. }
  21. }
  22. </script>
  23. <style scoped>
  24. </style>

相信看了以上介绍你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

相关阅读:


怎样使用Vue的自定义指令完成一个下拉菜单

JS怎样可以做到点击跳转到登陆的个人邮箱

nvm管理不同版本的node的方法

以上就是vue.js 里如何做到父向子组件传参的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行