5
4

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 3 years have passed since last update.

Vue.jsのコンポーネント内からhrefで画面遷移するには

Last updated at Posted at 2020-10-24

やりたかったこと

環境:Laravel + vue.js(単一Vueコンポーネント)

SPAではなく、普通に画面全体を遷移させる。
ただし、URLはbladeテンプレート側からpropsで受け取りvue側で他の変数と合体させるため可変にしたい。

URLが固定でいいなら以下のように普通のHTMLでいい。

<a href="/edit"></a>

で、この固定のURLの代わりにどうやってコンポーネント内のdataを埋め込むかというのが問題。
やり方がググっても出てこなかったのでかなりハマりました。
vue-rooterとかはいらないです。

解決法

aタグの場合

sample.vue
<template>
    <a :href="url_edit_id" class="btn btn-primary">編集</a>
</template>

<script>
    export default {
        props: ['url_edit'],
        data: function() { 
            return {
                url_edit_id:'/edit'
            }
        },
</script>

buttonタグの場合

ボタンタグの場はmethodsに任意の名前で関数を作成し、その中でlocation.href=[遷移させたいURL]を指定します。
そのmethod名をbuttonタグの中のv-on:clickの値として呼び出します。

sample.vue
<template>
    <button v-on:click="locate" class="btn btn-primary">編集</button>
</template>

<script>
    export default {
        props: ['url_edit'],
        data: function() { 
            return {
                url_edit_id:'/edit'
            }
        },
        methods: {
            locate: function() {
                location.href= this.url_edit_id;
            }
        },
</script>

aタグの場合とbuttonタグの場合で書いていますが、リンクへの挙動は同じです。
script側のdata内で定義した変数名をマスタッシュ{{ }}とかつけずにそのまま書きます。
不思議な構文ですが、これでurl_edit_idの値である/editがtemplate側に置換されて文字列展開されます。
aタグの方が簡単なので必要なければaタグにボタンのcss当てた方が簡単です。
私は:disabled属性を当てる必要があったのでボタンタグを使う必要がありました。

一応これで動きましたが、もっと簡単にかける方法あるよって方はコメントお願いします。

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?