[英]vue.js / vue-router - create instance of single file component with props to route to
[英]Vue.js: How to specify props in single file component?
我正在定義一個 文件組件
我想在該組件上使用props選項。
但是我在哪里可以添加代碼?
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
data () {
return {
// note: changing this line won't causes changes
// with hot-reload because the reloaded component
// preserves its current state and we are modifying
// its initial state.
msg: 'Hello World!'
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1 {
color: #42b983;
}
</style>
經過長時間的實驗,我找到了一個實用的解決方案:
項目文件結構:
src/
assets/
components/
Home.vue
App.vue
main.js
package.json
config.js
index.html
現在,我們要在vue-route
開啟的情況下訪問根組件——子組件Home.vue
中App
的 vm 字段。
主.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
Vue.use(VueRouter);
let router = new VueRouter();
router.map({
'/': {
name: 'home',
component: require('./components/Home')
}
});
router.start(App, 'body');
應用程序.vue:
<template>
<p>The current path: {{ $route.path }}.</p>
<p>Outer-Value: {{ outer_var }}</p>
<hr/>
<!-- The below line is very very important -->
<router-view :outer_var.sync="outer_var"></router-view>
</template>
<script>
import Home from './compnents/Home.vue'
export default {
replace: false,
components: { Home },
data: function() {
return {
outer_var: 'Outer Var Init Value.'
}
}
}
</script>
主頁.vue
<template>
<div>
<p><input v-model="outer_var" /></p>
<p>Inner-Value: {{ outer_var }}</p>
</div>
</template>
<script>
export default {
// relating to the attribute define in outer <router-view> tag.
props: ['outer_var'],
data: function () {
return {
};
}
}
</script>
請注意,內部道具將屬性綁定在組件標簽的屬性上(在本例中<router-view>
標簽。),而不是直接在父組件上。
因此,我們必須手動將傳遞的 props 字段綁定為組件標簽上的屬性。 見:http: //vuejs.org/guide/components.html#Passing-Data-with-Props
另外,請注意我在該屬性上使用了.sync
,因為默認情況下綁定是單向的:http: //vuejs.org/guide/components.html#Prop-Binding-Types
可以看到,通過嵌套組件共享狀態有點混亂。 為了更好地實踐,我們可以使用Vuex 。
你可以這樣做:
應用程序.js
<template>
<div class="hello">
<h1>{{ parentMsg }}</h1>
<h1>{{ childMsg }}</h1>
</div>
</template>
<script>
export default {
props: ['parentMessage'],
data () {
return {
childMessage: 'Child message'
}
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
new Vue({
el: '#app',
data() {
return {
message: 'Parent message'
}
},
render(h) {
return h(App, { props: { parentMessage: this.message } })
}
});
就像這樣,在調用 createApp() 時傳遞道具
查看圖片`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.