Подтвердить что ты не робот

Vue.js: Как указать реквизиты в одном файле?

Я определяю один файл

Я хочу использовать 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>
4b9b3361

Ответ 1

После долгого эксперимента я нашел практическое решение:

Структура файла проекта:

src/
  assets/
  components/
    Home.vue
  App.vue
  main.js
package.json
config.js
index.html

Теперь мы хотим получить доступ к корневым компонентам - App vm-полям внутри подкомпонента Home.vue, с vue-route on.

main.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');

App.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>

Home.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>

Заключение

Обратите внимание, что внутренний prop привязывает свойство к атрибуту тега компонента (<router-view> Tag в этом случае.), NOT непосредственно на родительском компоненте.

Итак, мы должны вручную привязать поле передающего реквизита как атрибут тега компонента. См.: http://vuejs.org/guide/components.html#Passing-Data-with-Props

Также обратите внимание, что я использовал .sync для этого атрибута, потому что привязка по умолчанию односторонняя вниз: http://vuejs.org/guide/components.html#Prop-Binding-Types

Вы можете видеть, что совместное использование статуса через компоненты вложенности немного запутано. Чтобы сделать лучшую практику, мы можем использовать Vuex.

Ответ 2

Вы можете сделать это следующим образом:

app.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 } })
  }
});

Ответ 3

Так как пару месяцев назад у Vue есть свой styleguide для ссылок и прочее подобное. Опоры - одна из ссылок, на самом деле важная.

BAD

props: ['status']

Хорошо

props: {
  status: String
}

Еще лучше

props: {
  status: {
    type: String,
    required: true,
    validator: function (value) {
      return [
        'syncing',
        'synced',
        'version-conflict',
        'error'
      ].indexOf(value) !== -1
    }
  }
}

Подробнее об этом здесь