<html>
<head>
<!-- 引入vue.js框架 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<bod>
<!-- 掛載點 vue在渲染時如需要會替換裏面的內容 在vue實例中綁定該id -->
<div id="app">
<!-- @click是v-on:click的簡寫 v-on指令用來綁定事件 -->
<h1 @click='handle'>welcome to {{address}}</h1>
<!-- :src是v-bind:src的簡寫 值爲表達式 可以直接引用data裏的變量 -->
<img :src="src" :title="'女神'+title" style="width: auto;height: 60%;">
</div>
</body>
<script type="text/javascript">
//用來指定掛載點 #號爲id選擇器
let el = "#app";
//用來綁定的model
let data = {
index:-1,
arr:["world","bejing","shanghai","shengzheng","guangzhou"],
address: "",
src:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545771989147&di=8c0778d85fdd69ee625e4aa73702dd38&imgtype=0&src=http%3A%2F%2Fi1.hdslb.com%2Fbfs%2Farchive%2F756409c04ec15855e8f7d27b957d1cbf5bfe2ed7.jpg",
titles: ["天使彥","彥"],
title: ""
};
/**
* ViewModel用來綁定model和view model爲data view通過el指定的視圖 DOM樹
* 可以通過app.$options.訪問el template methods
* 可以通過app.$options.data().或app.訪問data裏的元素
*/
var app = new Vue({
el: el,
// 有template 顯示hellow world 否則顯示welcome to world
// template:"<h1 @click='handle'>hellow {{address}}</h1>",
data: data,
methods: {
/**
* 手動調用(如在created方法裏調用)
* this爲methods app爲undefined
* 框架調用(如產生了通過@click指定的事件)
* this爲vue app爲vue
*/
handle: function(){
//如果是從created過來的 this只能訪問到handle方法和onclick方法
this.onclick();
},
onclick: function(){
data.address = data.arr[++data.index % data.arr.length];
data.title = data.titles[data.index % data.titles.length]
}
},
/**
* this爲vue對象 app爲undefined
*/
created: function(){
this.index = 2;
//template 放在methods裏無效
let text = "<h1 @click='handle'>address {{address}}</h1>";
// this.$options.template = text;
this.$options.methods.handle(this);
}
})
</script>
</html>