056_末晨曦Vue技术_处理边界情况之X-template

处理边界情况之X-template

点击打开视频讲解更加详细

另一个定义模板的方式是在一个<script>元素中,并为其带上 text/x-template 的类型,然后通过一个 id 将模板引用过去。例如:

<script type="text/x-template" id="hello-world-template">
  <p>Hello hello hello</p>
</script>
Vue.component('hello-world', {
  template: '#hello-world-template'
})

x-template 需要定义在 Vue 所属的 DOM 元素外。

这些可以用于模板特别大的 demo 或极小型的应用,但是其它情况下请避免使用,因为这会将模板和该组件的其它定义分离开。

完整案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>末晨曦吖</title>
</head>
<body>
    <div id="app">
        <hello-world></hello-world>
        <script type="text/x-template" id="hello-world-template">
            <p>Hello hello hello</p>
        </script>
    </div>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        Vue.component('hello-world', {
            template: '#hello-world-template'
        })
        var app = new Vue({
            el:'#app'
        })
    </script>
</body>
<style scoped>
    body{
        padding: 0;
        margin: 0;
    }
</style>
</html>

若对您有帮助,请点击跳转到B站一键三连哦!感谢支持!!!

posted @   程序猿咬棒棒糖拽天下  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示