首页 文章

Vuejs如何使用props将数据从main.js传递到App.vue

提问于
浏览
0

我遇到的问题是App组件和HelloWorld组件没有从main.js传递数据 . 在Vue中这应该是一件相当简单的事情 .
vue counter 10

您可以在图像中看到根元素已将计数器定义为10,它只是没有填充在任何子组件中 . 几乎像main.js中的第12行没有任何效果 . 如果我点击它,它会显示'counter:undefined' . 我究竟做错了什么?我一直在墙上撞了几个小时 .

这是我的main.js

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({

  components: {App},
  data: {
    counter: 10
  },
  template: '<App :counter="counter" />',
  //computed: {
  //  counterInc: function () {
  //    return this.counter++
  //  }
  //},
  methods: {
    updateCounter (x) {
      this.counter = x
    }
  },

  render: h => h(App)
}).$mount('#app')

这是我的App.vue

<template>
  <div id="app">
    <img alt="logo" src="./assets/logo.png">
    <HelloWorld msg="Our Message" :counter="counter"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app',
  props: ['counter'] ,
  components: {
    HelloWorld
  },
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

这是我的helloworld.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>
      Here lies all of our operations for automating some strenuous tasks. <br>
    </p>
    <h3>Get Started {{ counter }}</h3>
    <ul>
    <li><a v-on:click="updateCounter()" class="generateRollup">Generate Purchase Price</a></li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
    counter: String,
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #0093D0;
}
.generateRollup:hover {
  cursor: pointer;
}
</style>

2 回答

  • 0

    所以我并没有亲自使用 render 函数,但是如何让代码正常工作是在实际的html页面中提供初始模板并将Vue实例挂载到它 . 我在这里做了一个代码:https://codepen.io/crustyjew/pen/jeWPgY

    要点是删除你的 render 函数,将以下内容添加到html

    <div id="app">
      <app :counter="counter" />
    </div>
    

    留下 .$mount('#app') 将它挂载到你提供的html .

  • 1

    马蒂给了你一个答案,但你可能想要考虑一下你的项目结构 . 将数据从根组件传递到最低子组件不应该是目标 . 在您的情况下,您有两个选择:

    • 使用事件从组件中发出事件以更新另一个组件中的状态 . 有关更多信息,请参见https://vuejs.org/v2/guide/components-custom-events.html .

    • 使用像vuex这样的状态管理 . Vuex用于处理全局状态 . 您可以使用所有组件中的getter访问状态,而无需手动将数据传递给需要访问数据的每个组件 . 此外,vuex提供了动作/突变,允许您更新状态 . 有关更多信息,请参阅https://vuex.vuejs.org/ .

    对于小型项目,对于相同的结果,vuex可能需要很多开销 . 但是,如果您的项目变得越来越大,那么在通过多个组件传递数据时,很难知道组件中发生了什么 .

相关问题