dataview 可以从当前打开的页面进行查询吗

dataview 可以从当前打开「或者选中」的页面进行查询吗

平常是打开2个页面,其中一个是固定的,页面有dataview语句。
希望:随着另外一个页面的打开变化,那个固定页面页面内容会进行相应的变更。

1 个赞

你是想在dataview中监控打开的文件吗?

可参考

```dataviewjs
// 开始监控文件打开
onSomeFileOpened("all", (leaf, file) => {
	// 打开的文件是dataviewjs脚本所在文件时跳过
	if(dv.current().file.path === file) return;
	
	// dataview内容区输出
	dv.container.empty();
	dv.paragraph("你刚才打开了 " + file);
	//控制台打印打开的文件
	console.log(file, "opened @", new Date().toLocaleString());
	// 通知显示打开的文件路径
	new Notice(file + " opened.");
});

// 监控文件打开函数
// watches 待监控的文件,支持数组,watches有3种情况
// 当watches==all或空值(即!watches)时,代表监控所有文件
// 当为文件路径或数组时,代表只监控watches中的文件
// 当watches=["exclude", []]时,代表监控所有的文件,但排除watches[1]中的文件
// 注意:当watches内容被修改时,这时候应该重启obsidian,不然相当于开启了两个监控,因为是通过watches的内容来区分是否同一个监控的
// callback 第一个参数打开文件所在的leaf,第二个参数打开的文件路径
function onSomeFileOpened(watches, callback) {
    const timerKey = encodeURIComponent(watches.toString());
	if(!global[timerKey]) global[timerKey] = {};
	const onActiveLeafChange = async (activeLeaf) => {
		// 定时防止无效触发,只取最后一个触发
		if(global[timerKey]?.lastOpenedLeafTimer) clearTimeout(global[timerKey].lastOpenedLeafTimer)
		global[timerKey].lastOpenedLeafTimer = setTimeout(async () => {
	        // 获取文件路径
			let filePath = activeLeaf?.view.getState()?.file
			// 所有文件
			if(watches === "all" || !watches) {
				callback(activeLeaf, filePath);
			} 
			// 排除文件
			else if(watches[0] && watches[0] === "exclude" && watches[1] && watches[1].length > 0) {
				if(!watches[1].includes(filePath)) {
				    callback(activeLeaf, filePath);
				}
			}
			// 允许文件
			else if(watches.includes(filePath)) {
				callback(activeLeaf, filePath);
			}
		}, 42);
	};
	app.workspace.off("active-leaf-change", onActiveLeafChange);
	app.workspace.on('active-leaf-change', onActiveLeafChange);
	onActiveLeafChange(app.workspace.activeLeaf);
}
```
1 个赞
dataview 
table
without id "[["+file.name+"]] "+length(file.inlinks) as 引用数
from [[]]
sort length(file.inlinks) desc

比如这个代码目前只能展现:本篇笔记的反链接【from[[ 空]]】

如果把这个代码放到a笔记里,a笔记固定的。
然后我打开b笔记,a笔记代码就展现b笔记的反链接
打开c笔记,a笔记就展现c笔记的反链

这样是怎么实现的?

没看懂,筛选的文件只有一个,比如你这里说的b笔记或c笔记,那么leng(file.inlinks)也只有一条信息,你还排序干吗?

了解了,原来 from [[]] 这个语法查询的是反链的内容,我误以为查询的是当前文件本身。

[[]] lets you query from all files linking to the current file.

你直接按照我上面的代码,把调用函数改成这个吧

// 开始监控文件打开
onSomeFileOpened("all", async (leaf, file) => {
	// 打开的文件是dataviewjs脚本所在文件时跳过
	if(dv.current().file.path === file) return;
	
	// 查询反链
	const query=`
		table
		without id "[["+file.name+"]] "+length(file.inlinks) as 引用数
		from [[${file}]]
		sort length(file.inlinks) desc
	`;
	const result = await dv.query(query);
	const list = result.value.values;
	dv.container.empty();
	dv.table(['引用数'], list);
});

1112239999

1 个赞

好的,谢谢 :grinning: :pray: