首页 > 解决方案 > Vuejs如何使用props将数据从main.js传递到App.vue

问题描述

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

您可以在图像中看到根元素的计数器定义为 10,它只是没有填充到任何子组件中。几乎就像 main.js 中的第 12 行没有任何效果一样。如果我单击并显示“计数器:未定义”。我究竟做错了什么?几个小时以来,我一直在用头撞墙。

这是我的 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>

标签: javascriptvue.js

解决方案


所以我个人不怎么使用这个render函数,但是你可以做的是让你的代码工作是在实际的 html 页面中提供初始模板并将 Vue 实例挂载到它。我在这里做了一个codepen:https ://codepen.io/crustyjew/pen/jeWPgY

要点是删除您的render功能,将以下内容添加到html

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

离开.$mount('#app')把它挂载到你提供的那个html上。


推荐阅读