当我们编写Vue组件时候,组件中可能包含一系列的功能,例如一个代码仓库管理的应用,用户的仓库列表可以看做是一个组件,这个组件还包含筛选、搜索的功能。
所谓的功能我们可以理解为MVC中的Model和Controller。从视图角度,组件是最基本的代码复用单元,但是从逻辑上,功能模块是最基本的代码复用单元。
每个组件中可能包含多个功能(也称为关注点),而多个功能的代码会分散在Vue组件的各个部分:data/props/watch/computed/dom event callback/lifescycle。
这会带来两个问题:
为了解决上面两个问题,Vue需要提供功能模块级别的代码组织方式,即需要将同一个功能模块的代码写在同一片区域,而不是分散到组件的各个API中,另外还需要支持功能模块的封装,以便我们可以提取功能模块的代码进行复用。
如何实现上述两个能力呢?我们看看一个功能模块都包含哪些内容。
其中数据部分的代码写在Vue组件中的data、props中
数据计算部分的代码写在Vue组件中的computed和处理数据的方法中
数据更新部分代码写在生命周期钩子方法和交互事件中
数据监听代码写在watch中
因此我们希望Vue能提供一个API,让我们把一个功能模块(即关注点)的这些代码(包括data/props/computed/watch/dom event callback/lifecycle)都写在一起。并且能将其提取。
组合式API就提供了这样的能力。
总之,组合式API是在Vue3中新增加的API,它有两点优势:
前端面试刷题网站:灵题库,收集大厂面试真题,相关知识点详细解析。
开发者如何使用组合式API呢?简单地说,需要在Vue组件里实现setup方法,并在方法中返回一些方法和属性,返回的所有内容都将暴露给组件的其余部分 (计算属性、方法、生命周期钩子等等) 以及组件的模板。
首先看一个简单的例子,下面是一个单文件组件
<template>
<div id="app">
<span class="counter">
{{counter}}
<button @click="increase">+1</button>
</span>
<div class="msg-panel">
<span v-if="showMsg">
hello, world
</span>
<button @click="toggleShowCondition">{{showWhenOdd ? '奇数展示' : '偶数展示'}}</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
counter: 0,
showWhenOdd: true
};
},
computed: {
showMsg() {
return this.counter % 2 === 0
? this.showWhenOdd
: !this.showWhenOdd;
}
},
mounted() {
this.counter = Math.floor(Math.random() * 9) + 1;
},
methods: {
increase() {
this.counter++;
},
toggleShowCondition() {
this.showWhenOdd = !this.showWhenOdd;
}
}
};
</script>
<style scoped>
#app {
text-align: center;
margin-top: 60px;
}
.counter {
width: 100px;
height: 100px;
border: 1px solid;
padding: 10px;
}
.msg-panel {
width: 100px;
height: 100px;
margin: 50px auto;
border: 1px solid;
padding: 10px;
}
</style>
效果如下:

这个组件有两个功能
理解了上面的功能的实现之后我们再来看下使用组合式API如何实现相同的功能。
<template>
<div id="app">
<span class="counter">
{{counter}}
<button @click="increase">+1</button>
</span>
<div class="msg-panel">
<span v-if="showMsg">
hello, world
</span>
<button @click="toggleShowCondition">{{showWhenOdd ? '奇数展示' : '偶数展示'}}</button>
</div>
</div>
</template>
<script>
import {ref, onMounted, computed} from 'vue';
export default {
setup() {
// counter逻辑
const counter = ref(0);
const increase = () => {
counter.value++;
};
onMounted(() => {
counter.value = Math.floor(Math.random() * 9) + 1;
});
// 提示信息逻辑
const showWhenOdd = ref(true);
const showMsg = computed(() => {
return counter.value % 2 === 0
? showWhenOdd.value
: !showWhenOdd.value;
});
const toggleShowCondition = () => {
showWhenOdd.value = !showWhenOdd.value;
};
return {
counter,
increase,
showWhenOdd,
showMsg,
toggleShowCondition
};
}
};
</script>
<style scoped>
#app {
text-align: center;
margin-top: 60px;
}
.counter {
width: 100px;
height: 100px;
border: 1px solid;
padding: 10px;
}
.msg-panel {
width: 100px;
height: 100px;
margin: 50px auto;
border: 1px solid;
padding: 10px;
}
</style>
上面使用了组合式API的示例实现了相同的功能,注意:
对比两段代码我们可以看出,使用setup API的实现明显可以将两段功能逻辑(counter和展示提示信息)各自聚合在一起

这样就实现了我们之前提到的“让功能模块代码(关注点)聚合在一起,使可读性和可维护性更高”的效果,如果我们还希望实现“提供了一种功能模块级别的复用代码的方式”,我们可以这样组织代码:
<template>
<div id="app">
<span class="counter">
{{counter}}
<button @click="increase">+1</button>
</span>
<div class="msg-panel">
<span v-if="showMsg">
hello, world
</span>
<button @click="toggleShowCondition">{{showWhenOdd ? '奇数展示' : '偶数展示'}}</button>
</div>
</div>
</template>
<script>
import {ref, onMounted, computed} from 'vue';
const useCounter = () => {
// counter逻辑
const counter = ref(0);
const increase = () => {
counter.value++;
};
onMounted(() => {
counter.value = Math.floor(Math.random() * 9) + 1;
});
return {
counter,
increase
};
};
const useMsg = counter => {
const showWhenOdd = ref(true);
const showMsg = computed(() => {
return counter.value % 2 === 0
? showWhenOdd.value
: !showWhenOdd.value;
});
const toggleShowCondition = () => {
showWhenOdd.value = !showWhenOdd.value;
};
return {
showWhenOdd,
showMsg,
toggleShowCondition
};
};
export default {
setup() {
const {counter, increase} = useCounter();
const {showWhenOdd, showMsg, toggleShowCondition} = useMsg(counter);
return {
counter,
increase,
showWhenOdd,
showMsg,
toggleShowCondition
};
}
};
</script>
<style scoped>
#app {
text-align: center;
margin-top: 60px;
}
.counter {
width: 100px;
height: 100px;
border: 1px solid;
padding: 10px;
}
.msg-panel {
width: 100px;
height: 100px;
margin: 50px auto;
border: 1px solid;
padding: 10px;
}
</style>
通过上面示例可以看到,我们将不同的功能模块封装在函数中,并将关键数据和方法返回,然后在Vue组件的setup方法中引用并返回,就可以在模板中使用了。
除了上述的几个关键API:setup/ref/computed/onMounted,还有toRef用于解构props中的属性,watch用于监听数据,代替Vue组件中的watch属性。可以在官方文档查看用法。
尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是
我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?
我在理解Enumerator.new方法的工作原理时遇到了一些困难。假设文档中的示例:fib=Enumerator.newdo|y|a=b=1loopdoy[1,1,2,3,5,8,13,21,34,55]循环中断条件在哪里,它如何知道循环应该迭代多少次(因为它没有任何明确的中断条件并且看起来像无限循环)? 最佳答案 Enumerator使用Fibers在内部。您的示例等效于:require'fiber'fiber=Fiber.newdoa=b=1loopdoFiber.yieldaa,b=b,a+bendend10.times.m