Vue 起動時に html から Vue コンポーネントに変数を渡す

● Vue 起動時に html から Vue コンポーネントに変数を渡す

index.html に 渡したい引数をセット

<div id="app" arg1="hoge" arg2="fuga"></div>></div>

1. まず main.js で引数を受け取る

new Vue({
  render: h => h(App),
).$mount('#app')

↓ このように書き換えます

new Vue({
  render: function(createElement) {
    const arg1 = this.$el.getAttribute('arg1')
    alert( arg1 );
    return createElement(App,
      {
        props: {
          arg1: arg1
        }
      })
  }
}).$mount('#app')

2. 次に App.vue で引数を受け取る

export default {
  name: 'App',
  components: {
    MyComponent ,
  },
  props: {
    arg1: {
      type: String,
      required: true,
    } ,
  },
  created: function () {
    alert( 'App.vue : ' + this.arg1 );
  },
}
No.1969
03/12 09:26

edit