Vue.js v-onとコンポーネントの利用のサンプルコード

v-onとコンポーネントの登録と利用の仕方の簡単なサンプルコード
環境
- OS windows10 pro
- エディタ VScode
サンプルコード
下記のソースコードをindex.htmlとして作成する
vue.jsは開発バージョンを利用してます
<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body class="style1">
<div id="app">
<h3>v-on</h3>
<h4>this.message.split('').reverse().join('')が実行される</h4>
<p>{{ message }}</p>
<button class="button" v-on:click="reverseMessage">文字を反転</button>
</div>
<div id="app-2">
<h3>コンポーネント my-component利用</h3>
<my-component></my-component>
</div>
<div id="app-3">
<h3>コンポーネント todo-item利用</h3>
<todo-item
v-for="item in testList"
v-bind:todo="item"
v-bind:key="item.id"
></todo-item>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'む読らか対反'
},
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
// MyComponentを定義する
var MyComponent = Vue.extend({
template: '<div>コンポーネント</div>'
})
// componentに登録する
Vue.component('my-component', MyComponent)
// インスタンス作成
new Vue({
el: '#app-2'
})
// componentに登録する
Vue.component('todo-item', {
props: ['todo'],
template: '<p>{{ todo.text }}</p>'
})
// インスタンス作成
var app3 = new Vue({
el: '#app-3',
data: {
testList: [
{ id: 0, text: 'one' },
{ id: 1, text: 'two' },
{ id: 2, text: 'three' }
]
}
})
</script>
<style>
.style1 {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 120px;
}
h3 {
margin: 40px 0 0;
color: #41B883;
}
.button {
display: block;
position: relative;
margin: 0 auto;
width: 70pt;
border: solid 1px silver;
border-radius: 0.5rem 0.5rem;
padding: 0.5rem 1.5rem;
margin-top: 1rem;
text-decoration: none;
}
</style>
</body>
</html>
保存したファイルをブラウザで開いて確認

-
前の記事
npm ローカルインストールとグローバルインストールについて 2019.11.02
-
次の記事
Ubuntu19.10 GUIでIPアドレスを固定にする 2019.11.02
コメントを書く