javascript - Vuejs如何使用props将数据从main.js传递到App.vue
问题描述
我遇到了 App 组件和 HelloWorld 组件没有从 main.js 获取传递数据的问题。这在 Vue 中应该是一件相当简单的事情。
您可以在图像中看到根元素的计数器定义为 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>
解决方案
所以我个人不怎么使用这个render
函数,但是你可以做的是让你的代码工作是在实际的 html 页面中提供初始模板并将 Vue 实例挂载到它。我在这里做了一个codepen:https ://codepen.io/crustyjew/pen/jeWPgY
要点是删除您的render
功能,将以下内容添加到html
<div id="app">
<app :counter="counter" />
</div>
离开.$mount('#app')
把它挂载到你提供的那个html上。
推荐阅读
- python - Pygame icon() 函数不改变全局变量
- google-api - 试试这个 API for Logging API 返回“PERMISSION_DENIED”
- jquery - 如何使这些按钮充当无线电输入
- jquery - 为 margin-top jquery 设置动画时跳跃的 Safari 和 Firefox
- sql - 比较两个不同的客户列表
- python - 如何使用 setuptools 排除或忽略包预发布?
- android - 如何获取 ImageView 中的当前可绘制对象并将其转换为位图?
- python - What to assign to a variable to act like ":" in pandas dataframe .loc method?
- python - ValueError: (205087,) but got (1,),在 keras 的 onehot 向量上使用 fit_generator
- postgresql - 如何使用 docker image 和 azure 中的 postgres DB 在 terraform 中设置 sonarqube