深入了解Vue组件 — 处理边界情况(下)

4.模板定义的替代品

4.1 内联模板

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">      
        <style>
            .baseCss {
				border: 5px solid red;
				padding: 2rem;
			}
        </style>
        <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    </head>
    <body>
        <div id="app">
			<div1 inline-template>
				<div class="baseCss">
					<p>These are compiled as the component's own template.</p>
					<p>Not parent's transclusion content.</p>
				</div>
			</div1>		
        </div>
        <script>
            Vue.component('div1', {
                template: '<div></div>'
            });
			
            new Vue({
                el: '#app'
            });
        </script>
    </body>
</html>

内联模板使用inline-template

4.2 X-Template

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">      
        <style>
            
        </style>
        <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    </head>
    <body>
        <div id="app">
			<hello-world></hello-world>
        </div>
		<script type="text/x-template" id="hello-world-template">
			<p>Hello hello hello</p>
		</script>
        <script>
            Vue.component('hello-world', {
                template: '#hello-world-template'
            });
			
            new Vue({
                el: '#app'
            });
        </script>
    </body>
</html>

我们可以把模板定义在<script>元素中,其类型为text/x-template,通过 id 引用模板。

5.控制更新

5.1 强制更新

如果你依赖了一个未被Vue的响应式系统追踪的状态,需要动手动强制更新时,可以使用$forceUpdate

5.2 通过v-once创建低开销的静态组件

如果有一个组件包含了大量静态内容,你可以在根元素上添加v-once以确保这些内容只计算一次然后缓存起来。
参考:

原文地址:https://www.cnblogs.com/gzhjj/p/11798525.html