補充上一篇
App.vue
是可以有多個 instance
的
首先到 index.html
放兩個 app
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue</title>
</head>
<body>
<div id="app"></div>
<div id="app2"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
接著到 main.js
建立兩個 app
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import AppTwo from './AppTwo.vue'
createApp(App).mount('#app')
createApp(AppTwo).mount('#app2')
再新開一個 AppTwo.vue
與 App.vue
在同一層資料夾,內容可以一樣,也可以 import 自訂的元件
這邊我選擇使用原本的範例
npm run dev
之後會看到兩個 instance
同時出現在畫面中,其中 count
的值是不一樣的,由此可知它們有各自的生命週期、作用域,互不影響
正式進入今天的學習進度
<template>
<div class="hello-vite">
<h1>{{ title }}</h1> <!-- 會將 title 的值填入,若下方改變這邊也會跟著改動 -->
<p>This is my first Vue component</p>
<button @click="greet">Greet</button>
</div>
</template>
<script>
export default {
name: 'HelloVite',
data() {
return { // return 的物件為響應式狀態
title: 'Hello Vite!', //title 變數值 = 字串 'Hello Vite!'
count: 0
}
},
methods:{
greet(){
alert(`Vite Greet: Welcome User !!!`)
}
}
}
</script>
若雙大括號裡面裝的是 html 標籤,其值會被當成純文字解析,若要使其生效則使用 v-html
關鍵字
eg.
<template>
<div class="red_test">
<p>Using text interpolation: {{ rawHtml }}</p>
<p>Using v-html directive: <span v-html="rawHtml"></span></p>
</div>
</template>
<script>
export default {
name: 'red_test',
data() {
return {
rawHtml: '<span style="color:red">This should be red.</span>'
}
}
}
</script>
這樣的設計理念符合安全性,如果將直接傳入的變數解析為 HTML,會有 XSS 的風險,故預設皆解析為 text,所以當我們在使用 v-html
應該小心審慎
今日進度會停在這邊,預計明天從 v-bind
繼續學習
ref:
https://cn.vuejs.org/guide/essentials/application.html
https://ithelp.ithome.com.tw/m/articles/10347806
https://cn.vuejs.org/guide/essentials/template-syntax.html
https://zh.wikipedia.org/wiki/%E8%B7%A8%E7%B6%B2%E7%AB%99%E6%8C%87%E4%BB%A4%E7%A2%BC