>我在不同的页面上有这样的代码:
<div id="contact-us" class="section md-padding bg-grey">
<div id="contact"></div>
<script src="/dist/build.js"></script>
</div>
我有主要.js:
import Vue from 'vue'
import Contact from './Contact.vue'
new Vue({
el: '#contact',
render: h => h(Contact)
})
和 联系.vue 与模板
我想知道使用了哪个页面组件。所以我需要像div 一样从div 传递参数<div id="contact" page="main"></div>
.我该如何实现?
如何在 Vue.js 中将参数从div 传递到单页组件?
您不能从div 传递参数,因为它是 html 标记而不是自定义组件,您应该定义自己的组件来接受要传递的属性。
所以首先你应该定义你的组件并定义属性是允许接收,然后你使用你的组件,看看下面的例子,你可以在这里找到更多关于传递 props 的信息。
Vue.component('your-component', {
props: ['property'],
template: '<h3>{{ property }}</h3>'
})
new Vue({
el: '#app'
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
<your-component :property="'Hello props'" />
</div>
使用单个文件组件结构的示例。
父组件:
<template>
<ChildComponent :property="propValue" />
</template>
<script>
import childComponent from './childComponent.vue';
export default {
components: {
ChildComponent: childComponent
},
data() {
return {
propValue: 'Hello prop'
}
}
}
</script>
子组件:
<template>
<h3>{{ property }}</h3>
</template>
<script>
export default {
props: ['property'] // You can add more properties separeted by commas
}
</script>