「Vue.js」v-bindでhtmlタグの属性を削除するサンプル

2022年2月24日

環境
windows10 home 64bit
Vue.js 3.0.0
Google Chrome 98.0.4758.102

書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<button v-on:click="メソッド名" >実行</button>
methods: {
メソッド名: function (e) {
this.val = null
}
}
<button v-on:click="メソッド名" >実行</button> methods: { メソッド名: function (e) { this.val = null } }
<button v-on:click="メソッド名" >実行</button>
methods: {
    メソッド名: function (e) {
      this.val = null
        }
}

v-bindで指定した属性にnullをバインドして、属性を削除します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>htmlタグ属性を削除するサンプル</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
<strong :style="val"> study skill </strong>
<div >
<button v-on:click="run" >実行</button>
</div>
</div>
<script>
const cft = {
data() {
return {
val: 'color:red'
}
},
methods: {
run: function (e) {
this.val = null
}
}
}
Vue.createApp(cft).mount('#app')
</script>
</body>
</html>
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>htmlタグ属性を削除するサンプル</title> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="app"> <strong :style="val"> study skill </strong> <div > <button v-on:click="run" >実行</button> </div> </div> <script> const cft = { data() { return { val: 'color:red' } }, methods: { run: function (e) { this.val = null } } } Vue.createApp(cft).mount('#app') </script> </body> </html>
<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>htmlタグ属性を削除するサンプル</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
  <div id="app">
      <strong :style="val"> study skill </strong>
      <div >
        <button v-on:click="run" >実行</button>
      </div>
    </div>
  <script>
    const cft = {
      data() {
        return {
          val: 'color:red'
        }
      },
      methods: {
       run: function (e) {
          this.val = null
        }
      }
    }

    Vue.createApp(cft).mount('#app')

  </script>
</body>

</html>

結果
初期画面に「study skill」文字が「color:red」CSSが適用されます。
「実行」ボタンを押すと、strongタグに「style」属性にnullバインドさせるため黒字で表示されます。

Vue.js

Posted by arkgame