1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue-headで再度反映させる

Last updated at Posted at 2019-11-22

備忘録ですが、
「vue-head」を使っていて、たとえば「再検索」などをした場合、
同じページの中で再描画して、動的にタイトルやメタタグを変えたい、という事があるかとおもいます。
(正確にはmetaタグも含めてVue-headをもう一度実行したいな〜という時)
そういう場合は、


this.$emit('updateHead');

っていうのを追加してやります。
例えばこんな感じのソースがあるとして、

data () {
    return {
      title: 'sample',
    }
  },
head:{
  title: function () {
    return {
      inner: this.title;
    }
  },
},

axiosでdataを書き換えます。
そうするとデータは置き換わるけどheadの中身は変わってない状態ができます。

axios
  .get(
    apiserver
  )
  .then(response => {
    this.title = response.data.resource.data.title;
  })
  .catch(error => {
    window.alert(error);
  });

watchで監視して先程の一文を実行します。

watch: {
  'title':function(){
    this.$emit('updateHead');
  },
},

反映されます。

子コンポーネントから書き換える場合

コンポーネントが細かく分かれている場合があると思います。

Page.vue の中の Layout.vue の中の Navi.vue の中のボタンで axios を実行したりする場合、
Page.vue のタイトルを書き換えたいんだけど、値は子の子の中にあったりします。
そういう場合は・・・

this.$parent.$parent.title = this.hogehoge;
this.$parent.$parent.$emit('updateHead');

これで動くと思います。「なんだこのアホみたいな書き方は・・・」
って思うんですけどまあ…動くし、許して下さい。

このやり方って、使い所が微妙・・・

親コンポーネントに値を送った時点で、
親コンポーネント内で titlewatch で監視しておいたほうがスマートだと
ここまで書いて、思いました。

Vuex$storewatch するために、
computed$store.state.titlegetters で呼び出して、それを監視するという
のはちょっと面倒くさい。

そういう時は@click にまとめて書いておけばいいかなと。

<template>
  <button
    @click="refresh()"
  >
  ボタン
  </button>
</template>
methods:{
  refresh: function(){
    this.$store.dispatch('getMetaTitle');
    this.$parent.$parent.$emit('updateHead');
  },
},

そういう「全部書き換えは面倒くさいな」って時とか、しか使えません。以上です。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?