22. Outputting Raw HTML Content with v‐html - daniel-qa/Vue GitHub Wiki

22. Outputting Raw HTML Content with v-html

  • v-html, v-bind

替換了 HTML Content,和 網頁link,在 app.js 設定

<p {{outputGoal()}} </p> 會直接呼叫 vue methods 裡的函式

如果不使用 v-html="outputGoal(),只會輸出 html 的文本,vue 不會解析為 HTML

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Basics</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="app.js" defer></script>
  </head>
  <body>
    <header>
      <h1>Vue Course Goals</h1>
    </header>
    <section id="user-goal">
      <h2>My Course Goal</h2>
      <p v-html="outputGoal()"></p>      
      <p>Learn more <a v-bind:href="vueLink">about Vue</a>.</p>
    </section>
  </body>
</html>

app.js

const app = Vue.createApp({
    data() {
        return {
            courseGoalA: 'Finish the course and learn Vue!',
            courseGoalB: '<h2>Master Vue and build amazing apps!</h2>',
            vueLink: 'https://vuejs.org/'
        };
    },
    methods:{
        outputGoal(){
            const randomNumber = Math.random();
            if(randomNumber < 0.5){
                return this.courseGoalA;
            }else{
                return this.courseGoalB;
            }
        }
    }
});

app.mount('#user-goal');

  • this

this, 可以從 vue 控制的 html 代碼內部調用這些函數

 return this.courseGoalB;

⚠️ **GitHub.com Fallback** ⚠️