直接在浏览器中vue模板都可以写在那些位置

163 阅读1分钟

image.png

工程化的今天估计大家都快忘记直接在浏览器中使用vue了

在浏览器中直接使用 Vue 可以通过以下几种方式实现模板的编写:

1. 在 HTML 文件中直接编写 Vue 模板代码,以及绑定 Vue 组件的挂载点。例如:

<!DOCTYPE html>
<html>
<head>
  <title>Vue Example</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
  <div id="app">
    <h1>{{ message }}</h1>
  </div>
  <script>
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      }
    })
  </script>
</body>
</html>

2. 将 Vue 模板代码写在 HTML 文件的 <template> 标签中,并在 Vue 组件的 template 属性中引用。例如:

<!DOCTYPE html>
<html>
<head>
  <title>Vue Example</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
  <div id="app"></div>
  <template id="my-template">
    <h1>{{ message }}</h1>
  </template>
  <script>
    var app = new Vue({
      el: '#app',
      template: '#my-template',
      data: {
        message: 'Hello Vue!'
      }
    })
  </script>
</body>
</html>

3. 将 Vue 模板代码写在 JavaScript 文件中,并在 Vue 组件的 template 属性中引用。例如:

<!DOCTYPE html>
<html>
<head>
  <title>Vue Example</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <script src="my-component.js"></script>
</head>
<body>
  <div id="app"></div>
  <script>
    var app = new Vue({
      el: '#app',
      components: {
        'my-component': MyComponent
      }
    })
  </script>
</body>
</html>

my-component.js 文件的内容如下:

var MyComponent = {
  template: '<h1>{{ message }}</h1>',
  data: function() {
    return {
      message: 'Hello Vue!'
    }
  }
}

以上是三种在浏览器中直接使用 Vue 的模板编写方式。

当然还有一个方式是在script标签中定义

您可以使用 <script> 标签中的 type="text/x-template" 属性来定义模板。例如,以下是一个简单的 Vue 组件,它的模板写在了 HTML 文件中:

<!DOCTYPE html>
<html>
<head>
  <title>Vue Example</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
  <div id="app">
    <my-component></my-component>
  </div>

  <script type="text/x-template" id="my-component-template">
    <div>
      <h1>{{ message }}</h1>
      <button @click="increase">Increase</button>
    </div>
  </script>

  <script>
    Vue.component('my-component', {
      template: '#my-component-template',
      data: function() {
        return {
          message: 'Hello Vue!',
          count: 0
        }
      },
      methods: {
        increase: function() {
          this.count++;
        }
      }
    })

    var app = new Vue({
      el: '#app'
    })
  </script>
</body>
</html>

在上面的例子中,我们定义了一个 Vue 组件 my-component,并在 <script> 标签中定义了组件的模板。模板中包含了一个显示 message 的标题和一个可以增加 count 的按钮。

值得注意的是,我们使用了 @click 指令来监听按钮的点击事件,并调用组件的 increase 方法来更新 count 的值。这是 Vue 框架提供的一种方便的方式来处理 DOM 事件。

在上述例子中,我们还在 HTML 文件中的 <div> 中使用了 my-component 标签,这样就可以在页面中渲染出我们定义的组件。

最后,需要注意的是,使用 <script> 标签中的 type="text/x-template" 属性虽然是一种可行的方式,但是由于 HTML 的语义化问题,建议还是将组件的模板放在 JavaScript 文件中来使用。