ref 订阅
.net的关键字 [1]  ,ref关键字--让参数按照引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中;也等同将值类型的数据使用引用方式传参。若要使用ref参数,则方法定义和调用方法都必须显示使用ref关键字。ref是 Reference的缩写。 展开全文
.net的关键字 [1]  ,ref关键字--让参数按照引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中;也等同将值类型的数据使用引用方式传参。若要使用ref参数,则方法定义和调用方法都必须显示使用ref关键字。ref是 Reference的缩写。
信息
引用方法
显式使用
外文名
ref
用    途
C#中关键字通过引用传递参数
中文名
ref
proteus功能特点
例如:传递到ref参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。尽管ref和out在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用ref参数,而另一个方法采用out 参数,则无法重载这两个方法。注意:属性不是变量,因此不能作为ref参数传递。ref和out两个参数的不同在于:1、ref传进去的参数必须在调用前初始化,out不必,即:2、ref传进去的参数在函数内部可以直接使用,而out不可:3、ref传进去的参数在函数内部可以不被修改,但out必须在离开函数体前进行赋值。
收起全文
精华内容
下载资源
问答
  • 1、ref 加在普通的元素上,用this.ref.name 获取到的是dom元素 2、ref 加在子组件上,用this.ref.name 获取到的是组件实例,可以使用组件的所有方法。 3、如何利用 v-for 和 ref 获取一组数组或者dom 节点 普通的...
  • 为元素添加一个ref属性 该属性的值可任取 以作为该节点的引用名 ref即为reference(引用)的前三个字母 This is title This is content 用Vue实例中的自带的$refs属性获取元素 用预先定义好的引用名来获取 即在...
  • 主要介绍了React中Ref 的使用方法,结合实例形式总结分析了react中ref基本功能、用法及操作注意事项,需要的朋友可以参考下
  • REF30系列稳压芯片

    2019-04-23 17:50:56
    The REF30xx is a precision, low power, low voltage dropout voltage reference family available in a tiny SOT23-3.
  • 一、ref的基本使用 ref的使用 <!-- `vm.$refs.p`将会是DOM结点 --> <p ref=p>hello <!-- `vm.$refs.child`将会是子组件实例 --> <child ref=child> 如果在普通的 DOM 元素上使用,引用指向的就是DOM ...
  • 一个在JSON对象中转换$ref并将其替换为_ref的模块,以便可以将其存储在Mongo中,反之亦然。 我创建此模块是因为$ref是和的标准。 用法 import { replaceRefsJSON , replaceRefsMongo } from 'ref-replace' ; const...
  • ABB馈线保护测控装置REF611产品指南pdf,ABB馈线保护测控装置REF611产品指南:REF611 馈线保护测控装置,专为公用和工业配电系统的保护、控制、测量和监视而设计,可用于辐射型、环型或网络型配电网络,支持带有分布式...
  • ref

    千次阅读 2017-12-21 23:53:21
    Examples referencing ...var ref = require('ref') // so we can all agree that a buffer with the int value written // to it could be represented as an "int *" var buf = new Buffer

    Examples

    referencing and derefencing

    var ref = require('ref')
    
    // so we can all agree that a buffer with the int value written
    // to it could be represented as an "int *"
    var buf = new Buffer(4)
    buf.writeInt32LE(12345, 0)
    
    // first, what is the memory address of the buffer?
    console.log(buf.hexAddress())  // ← '7FA89D006FD8'
    
    // using `ref`, you can set the "type", and gain magic abilities!
    buf.type = ref.types.int
    
    // now we can dereference to get the "meaningful" value
    console.log(buf.deref())  // ← 12345
    
    
    // you can also get references to the original buffer if you need it.
    // this buffer could be thought of as an "int **"
    var one = buf.ref()
    
    // and you can dereference all the way back down to an int
    console.log(one.deref().deref())  // ← 12345

    See the full API Docs for more examples.

    The "type" interface

    You can easily define your own "type" objects at attach to Buffer instances. It just needs to be a regular JavaScript Object that contains the following properties:

    NameData TypeDescription
    sizeNumberThe size in bytes required to hold this type.
    indirectionNumberThe current level of indirection of the buffer. Usually this would be 1, and gets incremented on Buffers from ref() calls. A value of less than or equal to 0 is invalid.
    getFunction (buffer, offset)The function to invoke when dereferencing this type when the indirection level is 1.
    setFunction (buffer, offset, value)The function to invoke when setting a value to a buffer instance.
    nameString(optional) The name to use during debugging for this type.
    alignmentNumber(optional) The alignment of this type when placed in a struct. Defaults to the type's size.

    Be sure to check out the Wiki page of "Known Types", for the list of built-in ref types, as well as known external type implementations.

    For example, you could define a "bigint" type that dereferences into a bigint instance:

    var ref = require('ref')
    var bigint = require('bigint')
    
    // define the "type" instance according to the spec
    var BigintType = {
        size: ref.sizeof.int64
      , indirection: 1
      , get: function (buffer, offset) {
          // return a bigint instance from the buffer
          return bigint.fromBuffer(buffer)
        }
      , set: function (buffer, offset, value) {
          // 'value' would be a bigint instance
          var val = value.toString()
          return ref.writeInt64(buffer, offset || 0, val)
        }
    }
    
    // now we can create instances of the type from existing buffers.
    // "buf" is some Buffer instance returned from some external data
    // source, which should contain "bigint" binary data.
    buf.type = BigintType
    
    // and now you can create "bigint" instances using this generic "types" API
    var val = buf.deref()
                .add('1234')
                .sqrt()
                .shiftLeft(5)
     
     
     
     
     
     
     
     
      

    Turn Buffer instances into "pointers"

    What is ref?

    ref is a native addon for Node.js that aids in doing C programming in JavaScript, by extending the built-in Buffer class with some fancy additions like:

    • Getting the memory address of a Buffer
    • Checking the endianness of the processor
    • Checking if a Buffer represents the NULL pointer
    • Reading and writing "pointers" with Buffers
    • Reading and writing C Strings (NULL-terminated)
    • Reading and writing JavaScript Object references
    • Reading and writing int64_t and uint64_t values
    • A "type" convention to define the contents of a Buffer

    There is indeed a lot of meat to ref, but it all fits together in one way or another in the end. For simplicity, ref's API can be broken down into 3 sections:

    ref exports

    All the static versions of ref's functions and default "types" available on the exports returned from require('ref').

    "type" system

    The "type" system allows you to define a "type" on any Buffer instance, and then use generic ref() and deref() functions to reference and dereference values.

    Buffer extensions

    Buffer.prototype gets extended with some convenience functions. These all just mirror their static counterpart, using the Buffer's this variable as the buffer variable.


    ref exports

    This section documents all the functions exported from require('ref').

    ref.NULL ⇒ Buffer

    Buffer that references the C NULL pointer. That is, its memory address points to 0. Its length is 0 because accessing any data from this buffer would cause a segmentation fault.

    console.log(ref.NULL);
    <SlowBuffer@0x0 >
    

    ref.NULL_POINTER ⇒ Buffer

    NULL_POINTER is a pointer-sized Buffer instance pointing to NULL. Conceptually, it's equivalent to the following C code:

    char *null_pointer;
    null_pointer = NULL;
    

    ref.address(Buffer buffer→ Number

    • buffer - The buffer to get the memory address of.
    • Return: The memory address the buffer instance.

    Accepts a Buffer instance and returns the memory address of the buffer instance.

    console.log(ref.address(new Buffer(1)));
    4320233616
    
    console.log(ref.address(ref.NULL)));
    0
    

    ref.alloc(Object|String type? value→ Buffer

    • type - The "type" object to allocate. Strings get coerced first.
    • value - (optional) The initial value set on the returned Buffer, using type's set() function.
    • Return: A new Buffer instance with it's type set to "type", and (optionally) "value" written to it.

    Returns a new Buffer instance big enough to hold type, with the given value written to it.

    var intBuf = ref.alloc(ref.types.int)
    var int_with_4 = ref.alloc(ref.types.int, 4)
    

    ref.allocCString(String stringString encoding→ Buffer

    • string - The JavaScript string to be converted to a C string.
    • encoding - (optional) The encoding to use for the C string. Defaults to 'utf8'.
    • Return: The new Buffer instance with the specified String wrtten to it, and a trailing NUL byte.

    Returns a new Buffer instance with the given String written to it with the given encoding (defaults to 'utf8'). The buffer is 1 byte longer than the string itself, and is NUL terminated.

    var buf = ref.allocCString('hello world');
    
    console.log(buf.toString());
    'hello world\u0000'
    

    ref.coerceType(Object|String type→ Object

    • type - The "type" Object or String to coerce.
    • Return: A "type" object

    Coerces a "type" object from a String or an actual "type" object. String values are looked up from the ref.types Object. So:

    • "int" gets coerced into ref.types.int.
    • "int *" gets translated into ref.refType(ref.types.int)
    • ref.types.int gets translated into ref.types.int (returns itself)

    Throws an Error if no valid "type" object could be determined. Most ref functions use this function under the hood, so anywhere a "type" object is expected, a String may be passed as well, including simply setting the buffer.type property.

    var type = ref.coerceType('int **');
    
    console.log(type.indirection);
    3
    

    ref.deref(Buffer buffer→ ?

    • buffer - A Buffer instance to dereference.
    • Return: The returned value after dereferencing buffer.

    Accepts a Buffer instance and attempts to "dereference" it. That is, first it checks the indirection count of buffer's "type", and if it's greater than 1 then it merely returns another Buffer, but with one level less indirection.

    When buffer's indirection is at 1, then it checks for buffer.type which should be an Object with its own get() function.

    var buf = ref.alloc('int', 6);
    
    var val = ref.deref(buf);
    console.log(val);
    6
    

    ref.derefType(Object|String type→ Object

    • type - The "type" object to create a dereference type from. Strings get coerced first.
    • Return: The new "type" object with its indirection decremented by 1.

    Returns a new clone of the given "type" object, with its indirection level decremented by 1.

    ref.endianness ⇒ String

    A string that represents the native endianness of the machine's processor. The possible values are either "LE" or "BE".

    console.log(ref.endianness);
    'LE'
    

    ref.get(Buffer bufferNumber offsetObject|String type→ ?

    • buffer - The Buffer instance to read from.
    • offset - (optional) The offset on the Buffer to start reading from. Defaults to 0.
    • type - (optional) The "type" object to use when reading. Defaults to calling getType() on the buffer.
    • Return: Whatever value the "type" used when reading returns.

    Calls the get() function of the Buffer's current "type" (or the passed in type if present) at the given offset.

    This function handles checking the "indirection" level and returning a proper "dereferenced" Bufffer instance when necessary.

    ref.getType(Buffer buffer→ Object

    • buffer - The Buffer instance to get the "type" object from.
    • Return: The "type" object from the given Buffer.

    Returns the "type" property of the given Buffer. Creates a default type for the buffer when none exists.

    ref.isNull(Buffer buffer→ Boolean

    • buffer - The buffer to check for NULL.
    • Return: true or false.

    Accepts a Buffer instance and returns true if the buffer represents the NULL pointer, false otherwise.

    console.log(ref.isNull(new Buffer(1)));
    false
    
    console.log(ref.isNull(ref.NULL));
    true
    

    ref.readCString(Buffer bufferNumber offset→ String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The String that was read from buffer.

    Returns a JavaScript String read from buffer at the given offset. The C String is read until the first NULL byte, which indicates the end of the String.

    This function can read beyond the length of a Buffer.

    var buf = new Buffer('hello\0world\0');
    
    var str = ref.readCString(buf, 0);
    console.log(str);
    'hello'
    

    ref.readInt64BE(Buffer bufferNumber offset→ Number|String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The Number or String that was read from buffer.

    Returns a big-endian signed 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('int64');
    ref.writeInt64BE(buf, 0, '9223372036854775807');
    
    var val = ref.readInt64BE(buf, 0)
    console.log(val)
    '9223372036854775807'
    

    ref.readInt64LE(Buffer bufferNumber offset→ Number|String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The Number or String that was read from buffer.

    Returns a little-endian signed 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('int64');
    ref.writeInt64LE(buf, 0, '9223372036854775807');
    
    var val = ref.readInt64LE(buf, 0)
    console.log(val)
    '9223372036854775807'
    

    ref.readObject(Buffer bufferNumber offset→ Object

    • buffer - The buffer to read an Object from.
    • offset - The offset to begin reading from.
    • Return: The Object that was read from buffer.

    Reads a JavaScript Object that has previously been written to the given buffer at the given offset.

    var obj = { foo: 'bar' };
    var buf = ref.alloc('Object', obj);
    
    var obj2 = ref.readObject(buf, 0);
    console.log(obj === obj2);
    true
    

    ref.readPointer(Buffer bufferNumber offsetNumber length→ Buffer

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • length - (optional) The length of the returned Buffer. Defaults to 0.
    • Return: The Buffer instance that was read from buffer.

    Reads a Buffer instance from the given buffer at the given offset. The size parameter specifies the length of the returned Buffer instance, which defaults to 0.

    var buf = new Buffer('hello world');
    var pointer = ref.alloc('pointer');
    
    var buf2 = ref.readPointer(pointer, 0, buf.length);
    console.log(buf.toString());
    'hello world'
    

    ref.readUInt64BE(Buffer bufferNumber offset→ Number|String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The Number or String that was read from buffer.

    Returns a big-endian unsigned 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('uint64');
    ref.writeUInt64BE(buf, 0, '18446744073709551615');
    
    var val = ref.readUInt64BE(buf, 0)
    console.log(val)
    '18446744073709551615'
    

    ref.readUInt64LE(Buffer bufferNumber offset→ Number|String

    • buffer - The buffer to read a Buffer from.
    • offset - The offset to begin reading from.
    • Return: The Number or String that was read from buffer.

    Returns a little-endian unsigned 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('uint64');
    ref.writeUInt64LE(buf, 0, '18446744073709551615');
    
    var val = ref.readUInt64LE(buf, 0)
    console.log(val)
    '18446744073709551615'
    

    ref.ref(Buffer buffer→ Buffer

    • buffer - A Buffer instance to create a reference to.
    • Return: A new Buffer instance pointing to buffer.

    ref() accepts a Buffer instance and returns a new Buffer instance that is "pointer" sized and has its data pointing to the given Buffer instance. Essentially the created Buffer is a "reference" to the original pointer, equivalent to the following C code:

    char *buf = buffer;
    char **ref = &buf;
    

    ref.refType(Object|String type→ Object

    • type - The "type" object to create a reference type from. Strings get coerced first.
    • Return: The new "type" object with its indirection incremented by 1.

    Returns a new clone of the given "type" object, with its indirection level incremented by 1.

    Say you wanted to create a type representing a void *:

    var voidPtrType = ref.refType(ref.types.void);
    

    ref.reinterpret(Buffer bufferNumber sizeNumber offset→ Buffer

    • buffer - A Buffer instance to base the returned Buffer off of.
    • size - The length property of the returned Buffer.
    • offset - The offset of the Buffer to begin from.
    • Return: A new Buffer instance with the same memory address as buffer, and the requested size.

    Returns a new Buffer instance with the specified size, with the same memory address as buffer.

    This function "attaches" buffer to the returned Buffer to prevent it from being garbage collected.

    ref.reinterpretUntilZeros(Buffer bufferNumber sizeNumber offset→ Buffer

    • buffer - A Buffer instance to base the returned Buffer off of.
    • size - The number of sequential, aligned NULL bytes are required to terminate the buffer.
    • offset - The offset of the Buffer to begin from.
    • Return: A new Buffer instance with the same memory address as buffer, and a variable length that is terminated by size NUL bytes.

    Accepts a Buffer instance and a number of NULL bytes to read from the pointer. This function will scan past the boundary of the Buffer's length until it finds size number of aligned NULL bytes.

    This is useful for finding the end of NUL-termintated array or C string. For example, the readCString() function could be implemented like:

    function readCString (buf) {
      return ref.reinterpretUntilZeros(buf, 1).toString('utf8')
    }
    

    This function "attaches" buffer to the returned Buffer to prevent it from being garbage collected.

    ref.set(Buffer bufferNumber offset? valueObject|String type)

    • buffer - The Buffer instance to write to.
    • offset - The offset on the Buffer to start writing to.
    • value - The value to write to the Buffer instance.
    • type - (optional) The "type" object to use when reading. Defaults to calling getType() on the buffer.

    Calls the set() function of the Buffer's current "type" (or the passed in type if present) at the given offset.

    This function handles checking the "indirection" level writing a pointer rather than calling the set() function if the indirection is greater than 1.

    ref.writeCString(Buffer bufferNumber offsetString stringString encoding)

    • buffer - The Buffer instance to write to.
    • offset - The offset of the buffer to begin writing at.
    • string - The JavaScript String to write that will be written to the buffer.
    • encoding - (optional) The encoding to read the C string as. Defaults to 'utf8'.

    Writes the given string as a C String (NULL terminated) to the given buffer at the given offset. "encoding" is optional and defaults to 'utf8'.

    Unlike readCString(), this function requires the buffer to actually have the proper length.

    ref.writeInt64BE(Buffer bufferNumber offsetNumber|String input)

    • buffer - The buffer to write to.
    • offset - The offset to begin writing from.
    • input - This String or Number which gets written.

    Writes the input Number or String as a big-endian signed 64-bit int into buffer at the given offset.

    var buf = ref.alloc('int64');
    ref.writeInt64BE(buf, 0, '9223372036854775807');
    

    ref.writeInt64LE(Buffer bufferNumber offsetNumber|String input)

    • buffer - The buffer to write to.
    • offset - The offset to begin writing from.
    • input - This String or Number which gets written.

    Writes the input Number or String as a little-endian signed 64-bit int into buffer at the given offset.

    var buf = ref.alloc('int64');
    ref.writeInt64LE(buf, 0, '9223372036854775807');
    

    ref.writeObject(Buffer bufferNumber offsetObject object)

    • buffer - A Buffer instance to write object to.
    • offset - The offset on the Buffer to start writing at.
    • object - The Object to be written into buffer.

    Writes a pointer to object into buffer at the specified _offset.

    This function "attaches" object to buffer to prevent it from being garbage collected.

    var buf = ref.alloc('Object');
    ref.writeObject(buf, 0, { foo: 'bar' });
    

    ref.writePointer(Buffer bufferNumber offsetBuffer pointer)

    • buffer - A Buffer instance to write _pointer to.
    • offset - The offset on the Buffer to start writing at.
    • pointer - The Buffer instance whose memory address will be written to buffer.

    Writes the memory address of pointer to buffer at the specified offset.

    This function "attaches" object to buffer to prevent it from being garbage collected.

    var someBuffer = new Buffer('whatever');
    var buf = ref.alloc('pointer');
    ref.writePointer(buf, 0, someBuffer);
    

    ref.writeUInt64BE(Buffer bufferNumber offsetNumber|String input)

    • buffer - The buffer to write to.
    • offset - The offset to begin writing from.
    • input - This String or Number which gets written.

    Writes the input Number or String as a big-endian unsigned 64-bit int into buffer at the given offset.

    var buf = ref.alloc('uint64');
    ref.writeUInt64BE(buf, 0, '18446744073709551615');
    

    ref.writeUInt64LE(Buffer bufferNumber offsetNumber|String input)

    • buffer - The buffer to write to.
    • offset - The offset to begin writing from.
    • input - This String or Number which gets written.

    Writes the input Number or String as a little-endian unsigned 64-bit int into buffer at the given offset.

    var buf = ref.alloc('uint64');
    ref.writeUInt64LE(buf, 0, '18446744073709551615');
    

    ref._attach(Buffer bufferObject|Buffer object)

    • buffer - A Buffer instance to attach object to.
    • object - An Object or Buffer to prevent from being garbage collected until buffer does.

    Attaches object to buffer such that it prevents object from being garbage collected until buffer does.

    ref._reinterpret(Buffer bufferNumber sizeNumber offset→ Buffer

    • buffer - A Buffer instance to base the returned Buffer off of.
    • size - The length property of the returned Buffer.
    • offset - The offset of the Buffer to begin from.
    • Return: A new Buffer instance with the same memory address as buffer, and the requested size.

    Same as ref.reinterpret(), except that this version does not attach buffer to the returned Buffer, which is potentially unsafe if the garbage collector runs.

    ref._reinterpretUntilZeros(Buffer bufferNumber sizeNumber offset→ Buffer

    • buffer - A Buffer instance to base the returned Buffer off of.
    • size - The number of sequential, aligned NULL bytes that are required to terminate the buffer.
    • offset - The offset of the Buffer to begin from.
    • Return: A new Buffer instance with the same memory address as buffer, and a variable length that is terminated by size NUL bytes.

    Same as ref.reinterpretUntilZeros(), except that this version does not attach buffer to the returned Buffer, which is potentially unsafe if the garbage collector runs.

    ref._writeObject(Buffer bufferNumber offsetObject object)

    • buffer - A Buffer instance to write object to.
    • offset - The offset on the Buffer to start writing at.
    • object - The Object to be written into buffer.

    Same as ref.writeObject(), except that this version does not attach the Object to the Buffer, which is potentially unsafe if the garbage collector runs.

    ref._writePointer(Buffer bufferNumber offsetBuffer pointer)

    • buffer - A Buffer instance to write _pointer to.
    • offset - The offset on the Buffer to start writing at.
    • pointer - The Buffer instance whose memory address will be written to buffer.

    Same as ref.writePointer(), except that this version does not attach pointer to buffer, which is potentially unsafe if the garbage collector runs.


    "type" system

    A "type" in ref is simply an plain 'ol JavaScript Object, with a set of expected properties attached that implement the logic for getting & setting values on a given Buffer instance.

    To attach a "type" to a Buffer instance, you simply attach the "type" object to the Buffer's type property. ref comes with a set of commonly used types which are described in this section.

    Creating your own "type"

    It's trivial to create your own "type" that reads and writes your own custom datatype/class to and from Buffer instances using ref's unified API.
    To create your own "type", simply create a JavaScript Object with the following properties defined:

    NameData TypeDescription
    sizeNumberThe size in bytes required to hold this datatype.
    indirectionNumberThe current level of indirection of the buffer. When defining your own "types", just set this value to 1.
    getFunctionThe function to invoke when ref.get() is invoked on a buffer of this type.
    setFunctionThe function to invoke when ref.set() is invoked on a buffer of this type.
    nameString(Optional) The name to use during debugging for this datatype.
    alignmentNumber(Optional) The alignment of this datatype when placed inside a struct. Defaults to the type's size.

    The built-in "types"

    Here is the list of ref's built-in "type" Objects. All these built-in "types" can be found on the ref.types export Object. All the built-in types use "native endianness" when multi-byte datatypes are involved.

    types.void

    The void type.

    types.int8

    The int8 type.

    types.uint8

    The uint8 type.

    types.int16

    The int16 type.

    types.uint16

    The uint16 type.

    types.int32

    The int32 type.

    types.uint32

    The uint32 type.

    types.int64

    The int64 type.

    types.uint64

    The uint64 type.

    types.float

    The float type.

    types.double

    The double type.

    types.Object

    The Object type. This can be used to read/write regular JS Objects into raw memory.

    types.CString

    The CString (a.k.a "string") type.

    CStrings are a kind of weird thing. We say it's sizeof(char *), and indirection level of 1, which means that we have to return a Buffer that is pointer sized, and points to a some utf8 string data, so we have to create a 2nd "in-between" buffer.

    types.bool

    The bool type.

    Wrapper type around types.uint8 that accepts/returns true or false Boolean JavaScript values.

    types.byte

    The byte type.

    types.char

    The char type.

    types.uchar

    The uchar type.

    types.short

    The short type.

    types.ushort

    The ushort type.

    types.int

    The int type.

    types.uint

    The uint type.

    types.long

    The long type.

    types.ulong

    The ulong type.

    types.longlong

    The longlong type.

    types.ulonglong

    The ulonglong type.

    types.size_t

    The size_t type.


    Buffer extensions

    Buffer.prototype gets extended with some convenience functions that you can use in your modules and/or applications.

    Buffer#address()

    Shorthand for ref.address(this, …).

    Accepts a Buffer instance and returns the memory address of the buffer instance.

    console.log(ref.address(new Buffer(1)));
    4320233616
    
    console.log(ref.address(ref.NULL)));
    0
    

    Buffer#deref()

    Shorthand for ref.deref(this, …).

    Accepts a Buffer instance and attempts to "dereference" it. That is, first it checks the indirection count of buffer's "type", and if it's greater than 1 then it merely returns another Buffer, but with one level less indirection.

    When buffer's indirection is at 1, then it checks for buffer.type which should be an Object with its own get() function.

    var buf = ref.alloc('int', 6);
    
    var val = ref.deref(buf);
    console.log(val);
    6
    

    Buffer#hexAddress()

    Shorthand for ref.hexAddress(this, …).

    Buffer#inspect()

    ref overwrites the default Buffer#inspect() function to include the hex-encoded memory address of the Buffer instance when invoked.

    This is simply a nice-to-have.

    Before:

    console.log(new Buffer('ref'));
    <Buffer 72 65 66>
    

    After:

    console.log(new Buffer('ref'));
    <Buffer@0x103015490 72 65 66>
    

    Buffer#isNull()

    Shorthand for ref.isNull(this, …).

    Accepts a Buffer instance and returns true if the buffer represents the NULL pointer, false otherwise.

    console.log(ref.isNull(new Buffer(1)));
    false
    
    console.log(ref.isNull(ref.NULL));
    true
    

    Buffer#readCString()

    Shorthand for ref.readCString(this, …).

    Returns a JavaScript String read from buffer at the given offset. The C String is read until the first NULL byte, which indicates the end of the String.

    This function can read beyond the length of a Buffer.

    var buf = new Buffer('hello\0world\0');
    
    var str = ref.readCString(buf, 0);
    console.log(str);
    'hello'
    

    Buffer#readInt64BE()

    Shorthand for ref.readInt64BE(this, …).

    Returns a big-endian signed 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('int64');
    ref.writeInt64BE(buf, 0, '9223372036854775807');
    
    var val = ref.readInt64BE(buf, 0)
    console.log(val)
    '9223372036854775807'
    

    Buffer#readInt64LE()

    Shorthand for ref.readInt64LE(this, …).

    Returns a little-endian signed 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('int64');
    ref.writeInt64LE(buf, 0, '9223372036854775807');
    
    var val = ref.readInt64LE(buf, 0)
    console.log(val)
    '9223372036854775807'
    

    Buffer#readObject()

    Shorthand for ref.readObject(this, …).

    Reads a JavaScript Object that has previously been written to the given buffer at the given offset.

    var obj = { foo: 'bar' };
    var buf = ref.alloc('Object', obj);
    
    var obj2 = ref.readObject(buf, 0);
    console.log(obj === obj2);
    true
    

    Buffer#readPointer()

    Shorthand for ref.readPointer(this, …).

    Reads a Buffer instance from the given buffer at the given offset. The size parameter specifies the length of the returned Buffer instance, which defaults to 0.

    var buf = new Buffer('hello world');
    var pointer = ref.alloc('pointer');
    
    var buf2 = ref.readPointer(pointer, 0, buf.length);
    console.log(buf.toString());
    'hello world'
    

    Buffer#readUInt64BE()

    Shorthand for ref.readUInt64BE(this, …).

    Returns a big-endian unsigned 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('uint64');
    ref.writeUInt64BE(buf, 0, '18446744073709551615');
    
    var val = ref.readUInt64BE(buf, 0)
    console.log(val)
    '18446744073709551615'
    

    Buffer#readUInt64LE()

    Shorthand for ref.readUInt64LE(this, …).

    Returns a little-endian unsigned 64-bit int read from buffer at the given offset.

    If the returned value will fit inside a JavaScript Number without losing precision, then a Number is returned, otherwise a String is returned.

    var buf = ref.alloc('uint64');
    ref.writeUInt64LE(buf, 0, '18446744073709551615');
    
    var val = ref.readUInt64LE(buf, 0)
    console.log(val)
    '18446744073709551615'
    

    Buffer#ref()

    Shorthand for ref.ref(this, …).

    ref() accepts a Buffer instance and returns a new Buffer instance that is "pointer" sized and has its data pointing to the given Buffer instance. Essentially the created Buffer is a "reference" to the original pointer, equivalent to the following C code:

    char *buf = buffer;
    char **ref = &buf;
    

    Buffer#reinterpret()

    Shorthand for ref.reinterpret(this, …).

    Returns a new Buffer instance with the specified size, with the same memory address as buffer.

    This function "attaches" buffer to the returned Buffer to prevent it from being garbage collected.

    Buffer#reinterpretUntilZeros()

    Shorthand for ref.reinterpretUntilZeros(this, …).

    Accepts a Buffer instance and a number of NULL bytes to read from the pointer. This function will scan past the boundary of the Buffer's length until it finds size number of aligned NULL bytes.

    This is useful for finding the end of NUL-termintated array or C string. For example, the readCString() function could be implemented like:

    function readCString (buf) {
      return ref.reinterpretUntilZeros(buf, 1).toString('utf8')
    }
    

    This function "attaches" buffer to the returned Buffer to prevent it from being garbage collected.

    Buffer#writeCString()

    Shorthand for ref.writeCString(this, …).

    Writes the given string as a C String (NULL terminated) to the given buffer at the given offset. "encoding" is optional and defaults to 'utf8'.

    Unlike readCString(), this function requires the buffer to actually have the proper length.

    Buffer#writeInt64BE()

    Shorthand for ref.writeInt64BE(this, …).

    Writes the input Number or String as a big-endian signed 64-bit int into buffer at the given offset.

    var buf = ref.alloc('int64');
    ref.writeInt64BE(buf, 0, '9223372036854775807');
    

    Buffer#writeInt64LE()

    Shorthand for ref.writeInt64LE(this, …).

    Writes the input Number or String as a little-endian signed 64-bit int into buffer at the given offset.

    var buf = ref.alloc('int64');
    ref.writeInt64LE(buf, 0, '9223372036854775807');
    

    Buffer#writeObject()

    Shorthand for ref.writeObject(this, …).

    Writes a pointer to object into buffer at the specified _offset.

    This function "attaches" object to buffer to prevent it from being garbage collected.

    var buf = ref.alloc('Object');
    ref.writeObject(buf, 0, { foo: 'bar' });
    

    Buffer#writePointer()

    Shorthand for ref.writePointer(this, …).

    Writes the memory address of pointer to buffer at the specified offset.

    This function "attaches" object to buffer to prevent it from being garbage collected.

    var someBuffer = new Buffer('whatever');
    var buf = ref.alloc('pointer');
    ref.writePointer(buf, 0, someBuffer);
    

    Buffer#writeUInt64BE()

    Shorthand for ref.writeUInt64BE(this, …).

    Writes the input Number or String as a big-endian unsigned 64-bit int into buffer at the given offset.

    var buf = ref.alloc('uint64');
    ref.writeUInt64BE(buf, 0, '18446744073709551615');
    

    Buffer#writeUInt64LE()

    Shorthand for ref.writeUInt64LE(this, …).

    Writes the input Number or String as a little-endian unsigned 64-bit int into buffer at the given offset.

    var buf = ref.alloc('uint64');
    ref.writeUInt64LE(buf, 0, '18446744073709551615');
    

    展开全文
  • ABB REF542 plus保护功能配置手册pdf,ABB REF542 plus保护功能配置手册
  • ABB REF_615使用手册.pdf

    2019-09-05 17:12:15
    本手册详细介绍了馈线保护继电器REF_615的原理及操作。
  • ABB_REF615产品指南

    2019-01-29 13:58:52
    ABB REF615微机保护产品指南,用于产品的介绍、选型和推广
  • ABB多功能保护和开关控制装置REF542 plus操作手册pdf,ABB多功能保护和开关控制装置REF542 plus操作手册
  • REF_ET使用说明

    2015-12-25 03:49:07
    全面详细的讲解REF_ET软件的使用,并对各种方法深层分析
  • git-ref 通过获得当前的git参考。 安装 yarn add git-ref 用法 import { gitRef } from 'git-ref' ; const ref = gitRef ( ) ; console . log ( ref ) ; 执照 git-ref是MIT许可的开源项目。 请参阅。 版权:...
  • Vue3入门到精通--ref以及ref相关函数

    万次阅读 多人点赞 2020-10-27 14:58:38
    在Vue2.x通过给元素添加ref=‘xxx’,,然后使用refs.xxx的方式来获取元素 在Vue3.x中我们也可以通过ref来获取元素 用法 创建变量 import { ref } from 'vue' const count = ref(0) console.log(coun

    大家好,我是半夏👴,一个刚刚开始写文的沙雕程序员.如果喜欢我的文章,可以关注➕ 点赞 👍 加我微信:frontendpicker,邀你进群,一起学习交流前端,成为更优秀的工程师~关注公众号:半夏话前端,了解更多前端知识!点我探索新世界!

    系列文章目录

    1. Vue3入门到精通-setup
    2. Vue3入门到精通–ref以及ref相关函数
    3. Vue3入门到精通–reactive以及reactive相关函数

    创作不易 拒绝白嫖 点个赞呗
    关注我,带你走进前端的世界!!!


    是什么

    1. 将基础数据–>响应式数据 ==> 把值类型的数据包装编程响应式的引用类型的数据

    2. 函数

    3. 通过返回值的 value 属性获取响应式的值 ,修改也需要对 .value进行修改。

    4. 获取元素

      在Vue2.x通过给元素添加ref=‘xxx’,,然后使用refs.xxx的方式来获取元素

      在Vue3.x中我们也可以通过ref来获取元素

    用法

    创建变量

    import { ref } from 'vue'
    
    const count = ref(0)
    
    console.log(count.value) // 0
    
    count.value = 2
    
    console.log(count.value) // 2
    

    ref也可以接收复杂的数据类型作为参数,只是建议不使用ref处理复杂类型数据。

    在单文件组件中,不必写value,因为setup方法会自动解析

    <template>
      <div>
        <span>{{ count }}</span>
        <button @click="count ++">Increment count</button>
      </div>
    </template>
    

    获取元素

    <template>
        <div ref="refDiv">我是div</div>
    </template>
    
    <script>
    import {ref, onMounted} from 'vue';
    export default {
        name: 'App',
        setup() {
            let refDiv = ref(null); 
            onMounted(()=>{
                console.log('onMounted',refDiv.value);
                //  onMounted <div style=​"color:​ red;​">​我是div​</div>​
                refDiv.value.style.color="red"
                // 字体颜色变成红色
            });
    
            // setup 生命周期在mounted之前
            console.log(box.value);
            // null
    
            return {box};
        }
    }
    </script>
    

    ref和reactive的区别

    ref是把值类型添加一层包装,使其变成响应式的引用类型的值。

    reactive 则是引用类型的值变成响应式的值。

    所以两者的区别只是在于是否需要添加一层引用包装

    本质上

     ref(0)  --> reactive( { value:0 })
    

    注意点

    ref 对于 基本类型

    ref-创建出来的数据和以前无关(复制) 与js中的基本类型表现一致

    let a = 1;
    let aRef = ref(a);
    console.log(a, aRef.value); //1 1
    
    
    a = 2;
    console.log(a, aRef.value);// 2 1
    
    aRef.value = 3;
    console.log(a, aRef.value);// 2 3
    

    ref 对于 引用数据类型

    ref-创建出来的数据和以前相关(引用) 与js中的引用数据类型表现一致

    let obj = { name: "1" };
    let stateRef = ref(obj);
    console.log("obj", obj.name);
    console.log("ref", stateRef.value.name);
    // obj 1
    // ref 1
    
    stateRef.value.name = '2';
    console.log("obj", obj.name);
    console.log("ref", stateRef.value.name);
    // obj 2
    // ref 2
    
    
    obj.name='3'
    console.log("obj", obj.name);
    console.log("ref", stateRef.value.name);
    // obj 3
    // ref 3
    

    相关API

    isRef

    作用

    判断是都是ref对象

    其实内部是判断数据对象上是否包含__v_isRef 属性并且其值为 true

    用法

    const a = ref(a)
    const b = 'b'
    cosnole.log(isRef(a)) // true
    console.log(isRef(b)) // false
    

    unref

    如果参数为 ref,则返回内部值,否则返回参数本身。这是 val = isRef(val) ? val.value : val

    const temp=ref(3)  
    const newTemp = unref(1) // newTemp 确保现在是数字类型 3
    
    const a = unref(1) // a 确保现在是数字类型 1
    
    

    toRef

    作用

    引用数据类型转换为ref数据类型

    将reavtive数据类型转换为ref数据类型

    用法

    引用数据类型
    let obj = { name: "syl", age: "123" };
    let stateToref = toRef(obj, "name"); // 将name拿出来
    
    stateToref.value = "zs";
    console.log("obj", obj.name);
    console.log("ref", stateToref.value);
    // obj zs
    // ref zs
    
    
    obj.name = "ls";
    console.log("obj", obj.name);
    console.log("ref", stateToref.value);
    // obj ls
    // ref ls
    
    
    reactive数据类型
    let obj = reactive({ name: "syl", age: "123" });
    let stateToref = toRef(obj, "name"); // 将name拿出来
    
    stateToref.value = "zs";
    console.log("obj", obj.name);
    console.log("ref", stateToref.value);
    // obj zs
    // ref zs
    
    
    obj.name = "ls";
    console.log("obj", obj.name);
    console.log("ref", stateToref.value);
    // obj ls
    // ref ls
    

    注意点

    数据发生改变, 界面也不会自动更新

    案例1
    <p>toref----------{{ stateToref }}</p> // 这里显示的是zs
    
    let obj = { name: "syl" };
    let stateToref = toRef(obj, "name");
    
    stateToref.value = "zs";
    console.log("obj", obj.name);
    console.log("ref", stateToref.value);
    // obj zs
    // ref zs
    
    
    案例2
    <p>toref----------{{ stateToref }}</p>
    <button @click="changeToref">changeToref</button>   
    
    
    let obj = { name: "syl" };
    let stateToref = toRef(obj, "name");
    
    function changeToref() {
        stateToref.value = "ls";
        console.log("obj", obj.name);
        console.log("toref", stateToref.value);
    }
    // 点击changeToref,页面没有任何变化,仍然显示syl
    // console的结果是
    // obj ls
    // toref ls
    

    一个有意思的例子

       <p>toref----------{{ stateToref }}</p>
        <p>temp----------{{ temp }}</p>
        <button @click="changeToref">changeToref</button>
    
    let obj = { name: "syl" };
    let stateToref = toRef(obj, "name");
    let temp = ref("我是ref");
    
    function changeToref() {
    temp.value = "我是ref我改变啦!";
    stateToref.value = "ls";
    }
    // 点击按钮,页面的ui从
    toref----------syl
    temp----------我是ref
    // 变成
    oref----------ls
    temp----------我是ref我改变啦!
    
    这里可以看到ref触发了ui更新,导致toref的值也进行了更新
    
    其实不把这个ref的更新写到这个函数里面,比如新建函数,也会导致这个现象
    
    这个现象对其他函数也出现,例如shallowRef。
    

    toRefs

    作用

    批量转换。将响应式对象转换为普通对象,会将传入对象的每个属性处理为 ref 的值。

    官网例子

    当从合成函数返回响应式对象时,toRefs 非常有用,这样消费组件就可以在不丢失响应性的情况下对返回的对象进行分解/扩散:

    function useFeatureX() {
      const state = reactive({
        foo: 1,
        bar: 2
      })
      // 返回时转换为ref
      return toRefs(state)
    }
    
    export default {
      setup() {
        // 可以在不失去响应性的情况下破坏结构
        const { foo, bar } = useFeatureX()
    
        return {
          foo,
          bar
        }
      }
    }
    

    shallowRef 与triggerRef

    作用

    shallowRef

    创建一个 ref,它跟踪自己的 .value 更改,但不会使其值成为响应式的。也就是对value进行更新

    才会触发页面的更新,但是如果是一个引用数据类型,只对改引用数据进行值的修改,则不会触发更新。

    案例- 基本数据类型
    <p>{{ state1 }}</p>
    <button @click="myFn1">基本数据类型</button>
    
    let state1 = shallowRef(1);
    function myFn1() {
    	state1.value = 2;
    }
    // 点击按钮,页面会显2
    // 也就是对value进行修改可以触发页面更新
    
    
    案例- 引用数据类型
    <p>{{ state.a }}</p>
    <p>{{ state.b.c }}</p>
    <button @click="myFn1">引用数据类型-直接修改value</button>
    <button @click="myFn2">引用数据类型-对数据进行修改</button>
    
    let state = shallowRef({
        a: "a",
        b: {
            c: "c",
        },
    });
    
    function myFn1() {
        state.value={
            a: "a-new",
            b: {
                c: "c-new",
            },
        }
    }
    // 点击mufun1 页面从
    a
    c
    // 变成
    a-new
    c-new
    // 由此可以看出直接对value进行修改可以触发页面更新
    
    function myFn2() {
        state.value.a = "1";
        state.value.b.c = "1";
        console.log(state.value.a , state.value.b.c )
    }
    // 点击mufun2 页面仍然显示
    a
    c
    // console的结果是1 1
    
    triggerRef

    通常与shallowRef 一起使用,主要是主动触发界面更新的

    参数是ref变量

    <p>{{ state.a }}</p>
    <p>{{ state.b.c }}</p>
    <button @click="myFn2">使用triggerRef</button>
    
    let state = shallowRef({
        a: "a",
        b: {
            c: "c",
        },
    });
    function myFn2() {
        state.value.a = "1";
        state.value.b.c = "1";
        triggerRef(state);
    }
    // 点击mufun2 页面变成
    1
    1
    
    

    customRef

    自定义ref

    返回一个ref对象,可以显式地控制依赖追踪和触发响应

    <template>
      <div>
        <p>{{age}}</p>
        <button @click="myFn">按钮</button>
      </div>
    </template>
    
    import {ref, customRef} from 'vue';
    function myRef(value) {
      return customRef((track, trigger)=>{
        return {
          get(){
            track(); // 告诉Vue这个数据是需要追踪变化的
            console.log('get', value);
            return value;
          },
          set(newValue){
            console.log('set', newValue);
            value = "我的年龄==="+newValue;
            trigger(); // 告诉Vue触发界面更新
          }
        }
      });
    }
    
      setup() {
        // let age = ref(18); // reactive({value: 18})
        let age = myRef(18);
        function myFn() {
          age.value += 1;
        }
        return {age, myFn}
      }
    }
    
    // 页面显示的是18
    // 点击button按钮后,变成了我的年龄===19
    // 注意点:
    // 不能在get方法中发送网络请求
    
    
    
    
    展开全文
  • vue ref :refIn my previous post, I implemented my first Vue3 component. 在上一篇文章中,我实现了我的第一个Vue3组件。 I implementend a very simple web app (roll the dice) where I had a “div” where ...

    vue ref :ref

    In my previous post, I implemented my first Vue3 component.

    在上一篇文章中,我实现了我的第一个Vue3组件。

    I implementend a very simple web app (roll the dice) where I had a “div” where to show the result and a button to trigger the roll and generate a random number from 1 to 6.

    我实现了一个非常简单的Web应用程序(掷骰子),其中有一个显示结果的“ div ”和一个触发掷骰并生成1到6的随机数的按钮。

    In that case, I used “ref()” to create reactive properties.

    在那种情况下,我使用“ ref() ”来创建React特性。

    “My first Vue3 component” article where I used ref() for declaring reactive properties: https://medium.com/swlh/my-first-vue3-component-6e1ef1670544

    我使用ref()声明React性的“我的第一个Vue3组件”文章: https ://medium.com/swlh/my-first-vue3-component-6e1ef1670544

    ref()“方法” (The ref() “approach”)

    For example in “setup()” function of my component I declared “dice” property in order to store the last result of the roll action.

    例如,在我组件的“ setup() ”函数中,我声明了“ dice ”属性,以便存储滚动动作的最后结果。

    Image for post

    The “dice” property was an integer, initialized with 0. To make it reactive, I used “ref()” function to initialize it. So “dice” it was not just a simple integer but an object:

    dice ”属性是一个整数,初始化为0 。 为了使其具有React性,我使用“ ref() ”函数对其进行了初始化。 因此,“ 骰子 ”不仅是一个简单的整数,而且是一个对象:

    const dice = ref(0);
    Image for post
    The property “dice” is not just a simple integer. It is a object with value attribute
    属性“骰子”不仅仅是一个简单的整数。 它是具有值属性的对象

    In this way “dice” is a object with “value” attribute. This means that, if you want to access to the “dice” value in your component, you need to use “dice.value”.

    这样,“ 骰子 ”是具有“ ”属性的对象。 这意味着,如果要访问组件中的“ dice ”值,则需要使用“ dice.value ”。

    从ref()到react() (From ref() to reactive())

    Another way to make the properties reactive is to use “reactive()” function.

    使属性具有React性的另一种方法是使用“ react() ”函数。

    The first difference from developer perspective is that using “ref()” you need to declare each single property

    从开发人员的角度来看,第一个区别是使用“ ref() ”时,您需要声明每个属性

    const dice = ref(0);
    const rolls = ref([]);

    and when you send the properties too the template you need to list them individually:

    当您也发送属性模板时,您需要单独列出它们:

    return { dice, rolls, total, roll, restart };

    With “reactive()” function you need to collect all properties in one object:

    使用“ react() ”函数,您需要将所有属性收集到一个对象中:

    const game = reactive(
    {
    dice: 0,
    rolls: []
    }
    )

    With this syntax you can pass to the template just the object (game object) instead of all properties (dice, rolls…):

    使用这种语法,您可以仅将对象(游戏对象)而不是所有属性(骰子,掷骰子……)传递给模板:

    return {
    game, //data
    roll, restart //functions
    };

    Another difference is in the properties usage. You can avoid to use “.value” but you need to use it as object attribute “game.dice”. For example:

    另一个不同之处在于属性用法。 您可以避免使用“ .value ”,但需要将其用作对象属性“ game.dice ”。 例如:

    function restart() {
    game.dice=0
    game.rolls = [];
    }

    An additional thing: if you want to avoid to use “game.dice” and “game.rolls” and you want use just “dice” and “rolls”, you could use the object destructuring when you send properties to template (in the return clausole of setup method).

    另一件事:如果要避免使用“ game.dice ”和“ game.rolls ”,而只想使用“ dice ”和“ rolls ”,则可以在将属性发送到模板时使用对象分解 (在返回设置方法的步骤)。

    模板 (The template)

    Thanks to the usage of destructuring object, the template is still the same of “ref()” approach.

    由于使用了解构对象,因此模板仍然与“ ref() ”方法相同。

    <template>
    <h1>Number is: {{ dice }}</h1>
    <div>Number of rolls: {{ rolls.length }}</div>
    <div>Total: {{ total }}</div>
    <button @click="roll()">Let's roll the dice</button>
    <button @click="restart()">Restart</button>
    <ul>
    <li v-for="(t, index) in rolls" :key="index">
    {{ t }}
    </li>
    </ul>
    </template>

    遍历代码 (Walking through the code)

    <script>
    // ##001 : import from vue3:
    // - reactive for making properties reactive;
    // - computed for computed function like total
    // - toRefs for destructuring object for template
    import { reactive, computed, toRefs } from "vue";
    export default {
    name: 'RollTheDiceReactive',
    // ##002 : implement setup function
    setup() {
    // ##003 : declare and initialize reactive object
    const game = reactive(
    {
    dice: 0,
    rolls: [],
    // ##004 : we include also computed properties in game object
    total: computed(
    () => {
    let temptotal = 0;
    for (let i=0 ; i< game.rolls.length; i++) {
    temptotal = temptotal + game.rolls[i]
    }
    return temptotal;
    }
    )
    }
    )
    // ##005: implement roll function (inside setup() )
    function roll() {
    game.dice = Math.floor(Math.random() * Math.floor(5)) + 1;
    game.rolls.unshift(game.dice);
    }// ##06: implement restart function (inside setup() )
    function restart() {
    game.dice=0
    game.rolls = [];
    }// ##007: expose to the template all stuff (object, functions etc)
    return {
    ...toRefs(game), //data
    roll, restart //functions
    };
    }
    }
    </script>
    • ##001 import from vue3: reactive (for making properties reactive), computed (for computed functions), toRefs (for destructuring object for template);

      ## 001从vue3导入: React式 (用于使属性具有React性), 计算式 (用于计算函数), toRefs (用于模板的解构对象);

    • ##002 setup function: with composition API in Vue3 we need to implement the setup function. Setup function will contain and will return an object (see point ##007) and functions needed by template;

      ## 002设置功能:在Vue3中使用复合API,我们需要实现设置功能。 设置函数将包含并返回一个对象(请参阅第#007点)和模板所需的函数;
    • ##003 declare the reactive object with properties and also computed properties. To make it reactive we will use “reactive()” function;

      ## 003使用属性和计算属性声明React对象。 为了使其具有React性,我们将使用“ react() ”函数;

    • ##004 we can include also “computed properties” in the reactive object. You can access to computed properties accessing to the object properties (game.total in this case);

      ## 004我们还可以在React对象中包含“计算属性”。 您可以访问计算属性,而访问对象属性(在这种情况下为game.total );

    • ##005 implement the roll() function in order to change the value of dice and adding on top of the array rolls the new dice value (to keep track of all rolls);

      ## 005实现roll()函数以更改骰子的值,并在数组的顶部添加新的骰子值(以跟踪所有掷骰 );

    • ##006 implement the restart() function in order to re-initialize “dice” and “rolls” (we are accessing to them as object attribute);

      ## 006实现restart()函数,以便重新初始化“ dice ”和“ rolls ”(我们将它们作为对象属性访问);

    • ##007 this is a new thing for Vue2 users (because the setup() method). We need to return an object with all stuff needed in the template. In order to access directly to attributes in the template as “dice” instead of “game.dice” you need to use destricturing functionality (…object). To keep the destructured object reactive, you need to use “…toRef(object)”. If you don’t use “toRef()” and you try to use just“…object”, you will loose the reactivity of the properties.

      ## 007这对Vue2用户来说是新事物(因为setup()方法)。 我们需要返回一个对象,其中包含模板中所需的所有内容。 为了直接以“ dice ”(而不是“ game.dice ”)访问模板中的属性,您需要使用限制功能( …object )。 要使已变形的对象保持React状态,您需要使用“ …toRef(object) ”。 如果不使用“ toRef() ”,而仅尝试使用“ …object ”,则会失去属性的React性。

    Image for post
    The Vue3 “reactive()” component
    Vue3“ reactive()”组件

    翻译自: https://medium.com/swlh/vue3-using-ref-or-reactive-88d47c8f6944

    vue ref :ref

    展开全文
  • 一文搞懂 React ref

    千次阅读 2020-12-02 08:43:00
    最近也开始研究React,这篇文章主要是讲述 Ref 相关的内容,如有错误请指正。ref 的由来在典型的 React 数据流中,props 是父组件与子组件交互的唯一方式。要修改一个子组...

    最近也开始研究React,这篇文章主要是讲述 Ref 相关的内容,如有错误请指正。

    ref 的由来

    在典型的 React 数据流中,props 是父组件与子组件交互的唯一方式。要修改一个子组件,你需要使用新的 props 来重新渲染它。但是,在某些情况下,你需要在典型数据流之外强制修改子组件/元素。

    适合使用 refs 的情况:

    • 管理焦点,文本选择或媒体播放。

    • 触发强制动画。

    • 集成第三方 DOM 库。

    ref 的三种方式

    在 React v16.3 之前,ref 通过字符串(string ref)或者回调函数(callback ref)的形式进行获取。

    ref 通过字符获取:

    // string ref
    class MyComponent extends React.Component {
      componentDidMount() {
        this.refs.myRef.focus();
      }
    
      render() {
        return <input ref="myRef" />;
      }
    }
    

    ref 通过回调函数获取:

    // callback ref
    class MyComponent extends React.Component {
      componentDidMount() {
        this.myRef.focus();
      }
    
      render() {
        return <input ref={(ele) => {
          this.myRef = ele;
        }} />;
      }
    }
    

    在 v16.3 中,经 0017-new-create-ref 提案引入了新的 API:React.createRef

    ref 通过 React.createRef 获取:

    // React.createRef
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
      }
    
      componentDidMount() {
        this.myRef.current.focus();
      }
      
      render() {
        return <input ref={this.myRef} />;
      }
    }
    

    将被移除的 string ref

    首先来具体说说 string ref,string ref 就已被诟病已久,React 官方文档中如此声明:"如果你目前还在使用 this.refs.textInput 这种方式访问 refs ,我们建议用回调函数或 createRef API 的方式代替。",为何如此糟糕?

    最初由 React 作者之一的 dan abramov。发布于https://news.ycombinator.com/edit?id=12093234,(该网站需要梯子)。吐槽内容主要有以下几点:

    1. 3.string ref 不可组合。例如一个第三方库的父组件已经给子组件传递了 ref,那么我们就无法再在子组件上添加 ref 了。另一方面,回调引用没有一个所有者,因此您可以随时编写它们。例如:

      /** string ref **/
      class Parent extends React.Component {
        componentDidMount() {
          // 可获取到 this.refs.childRef
          console.log(this.refs);
        }
        render() {
          const { children } = this.props;
          return React.cloneElement(children, {
            ref: 'childRef',
          });
        }
      }
      
      class App extends React.Component {
        componentDidMount() {
          // this.refs.child 无法获取到
          console.log(this.refs);
        }
        render() {
          return (
            <Parent>
              <Child ref="child" />
            </Parent>
          );
        }
      }
      
    2. 2.string ref 的所有者由当前执行的组件确定。这意味着使用通用的“渲染回调”模式(例如react),错误的组件将拥有引用(它将最终在react上而不是您的组件定义renderRow)。

      class MyComponent extends Component {
        renderRow = (index) => {
          // string ref 会挂载在 DataTable this 上
          return <input ref={'input-' + index} />;
      
          // callback ref 会挂载在 MyComponent this 上
          return <input ref={input => this['input-' + index] = input} />;
        }
      
        render() {
          return <DataTable data={this.props.data} renderRow={this.renderRow} />
        }
      }
      
    3. 3.string ref 不适用于Flow之类的静态分析。Flow不能猜测框架可以使字符串ref“出现”在react上的神奇效果,以及它的类型(可能有所不同)。回调引用比静态分析更友好。

    4. 4.string ref 强制React跟踪当前正在执行的组件。这是有问题的,因为它使react模块处于有状态,并在捆绑中复制react模块时导致奇怪的错误。在 reconciliation 阶段,React Element 创建和更新的过程中,ref 会被封装为一个闭包函数,等待 commit 阶段被执行,这会对 React 的性能产生一些影响。

    关于这点可以参考 React 源码 coerceRef 的实现:

    在调和子节点得过程中,会对 string ref 进行处理,把他转换成一个方法,这个方法主要做的事情就是设置 instance.refs[stringRef] = element,相当于把他转换成了function ref

    对于更新得过程中string ref是否变化需要对比得是 current.ref._stringRef,这里记录了上一次渲染得时候如果使用得是string ref他的值是什么

    owner是在调用createElement的时候获取的,通过ReactCurrentOwner.current获取,这个值在更新一个组件前会被设置,比如更新ClassComponent的时候,调用render方法之前会设置,然后调用render的时候就可以获取对应的owner了。

    坚挺的 callback ref

    React 将在组件挂载时,会调用 ref 回调函数并传入 DOM 元素,当卸载时调用它并传入 null。在 componentDidMount 或 componentDidUpdate 触发前,React 会保证 refs 一定是最新的。

    如果 ref 回调函数是以内联函数的方式定义的,在更新过程中它会被执行两次,第一次传入参数 null,然后第二次会传入参数 DOM 元素。这是因为在每次渲染时会创建一个新的函数实例,所以 React 清空旧的 ref 并且设置新的。通过将 ref 的回调函数定义成 class 的绑定函数的方式可以避免上述问题,但是大多数情况下它是无关紧要的。

    最新的 React.createRef

    React.createRef 的优点:

    • 相对于 callback ref 而言 React.createRef 显得更加直观,避免了 callback ref 的一些理解问题。

    React.createRef 的缺点:

    1. 性能略低于 callback ref

    2. 能力上仍逊色于 callback ref,例如上一节提到的组合问题,createRef 也是无能为力的。

    ref 的值根据节点的类型而有所不同:

    • 当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性。

    • 当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性。

    • 默认情况下,你不能在函数组件上使用 ref 属性(可以在函数组件内部使用),因为它们没有实例:

      • 如果要在函数组件中使用 ref,你可以使用 forwardRef(可与 useImperativeHandle 结合使用)

      • 或者可以将该组件转化为 class 组件。

    Refs 转发

    是否需要将 DOM Refs 暴露给父组件?

    在极少数情况下,你可能希望在父组件中引用子节点的 DOM 节点。通常不建议这样做,因为它会打破组件的封装,但它偶尔可用于触发焦点或测量子 DOM 节点的大小或位置。

    如何将 ref 暴露给父组件?

    如果你使用 16.3 或更高版本的 React, 这种情况下我们推荐使用 ref 转发。Ref 转发使组件可以像暴露自己的 ref 一样暴露子组件的 ref。

    什么是 ref 转发?

    const FancyButton = React.forwardRef((props, ref) => (
      <button ref={ref} className="FancyButton">
        {props.children}
      </button>
    ));
    
    // 你可以直接获取 DOM button 的 ref:
    const ref = React.createRef();
    <FancyButton ref={ref}>Click me!</FancyButton>;
    

    如果再低版本中如何转发?

    如果你使用 16.2 或更低版本的 React,或者你需要比 ref 转发更高的灵活性,你可以使用 ref 作为特殊名字的 prop 直接传递。

    比如下面这样:

    function CustomTextInput(props) {
      return (
        <div>
          <input ref={props.inputRef} />
        </div>
      );
    }
    
    class Parent extends React.Component {
      constructor(props) {
        super(props);
        this.inputElement = React.createRef();
      }
      render() {
        return (
          <CustomTextInput inputRef={this.inputElement} />
        );
      }
    }
    

    以下是对上述示例发生情况的逐步解释:

    1. 我们通过调用 React.createRef 创建了一个 React ref 并将其赋值给 ref 变量。

    2. 我们通过指定 ref 为 JSX 属性,将其向下传递给 <FancyButton ref={ref}>

    3. React 传递 ref 给 forwardRef 内函数 (props, ref) => ...,作为其第二个参数。

    4. 我们向下转发该 ref 参数到 <button ref={ref}>,将其指定为 JSX 属性。

    5. 当 ref 挂载完成,ref.current 将指向 <button> DOM 节点。

    最后

    如果你觉得这篇内容对你挺有启发,我想邀请你帮我三个小忙:

    1. 点个「在看」,让更多的人也能看到这篇内容(喜欢不点在看,都是耍流氓 -_-)

    2. 欢迎加我微信「qianyu443033099」拉你进技术群,长期交流学习...

    3. 关注公众号「前端下午茶」,持续为你推送精选好文,也可以加我为好友,随时聊骚。

    点个在看支持我吧,转发就更好了

    展开全文
  • C++11的std::ref、std::cref源码解析

    万次阅读 多人点赞 2021-05-09 11:13:21
    C++11的std::ref、std::cref源码解析1、源码准备2、std::ref和std::cref的作用3、std::ref相关源码解析3.1、std::ref解析3.1、std::reference_wrapper解析3.3、std::remove_cv解析3.4、std::_Reference_wrapper_base...
  • vue3中效率为什么会提升很多,composition-api 和ref reactive、setup 等详解,带你更快的学习,使用vue3.0。
  • node-ffi ref模块使用详解

    千次阅读 2018-06-13 16:17:46
    Turn Buffer instances into "...ref is a native addon for Node.js that aids in doing C programming in JavaScript, by extending the built-in Buffer class with some fancy additions like...
  • vue中ref标签属性和$ref的关系,

    千次阅读 2019-09-28 18:13:08
    Vue给我们提供了一个专门用来获取DOM节点的方法 ,使用元素的ref属性,使用起来非常方便 (这只是用于偶尔vue需要操作节点时候才使用) vue的ref属性 ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件...
  • vue 3.0新特性之reactive与ref

    千次阅读 2020-07-30 14:02:03
    const count = ref(0) const state = reactive({ count }) console.log(state.count) // 0 state.count = 1 console.log(count.value) // 1 reactive属性绑定新的ref对象后,原来ref的value不变(断开了)。...
  • ABB 公司 REF 615微机保护通信规约介绍,主要介绍该保护装置的三遥信息、微机保护信号、事件上传的MODBUS定义,是电力通信技术人员需要接入ABB保护必须的资料
  • React ref、forwardRef 和useRef的学习

    千次阅读 2020-03-11 10:56:58
    关于ref 组件内使用ref,获取dom元素 class Test extends Component { constructor(props) { super(props); this.state = { myDiv:createRef() } } componentDidMount(){ console.log("this.myDi...
  • ref 的三种用法

    千次阅读 2020-02-27 01:25:08
    ref 有三种用法:  1、ref 加在普通的元素上,用this.$refs.(ref值) 获取到的是dom元素 2、ref 加在子组件上,用this.refs.(ref值)获取到的是组件实例,可以使用组件的所有方法。在使用方法的时候直接this...
  • ember-ref-修饰符 首先检查 ! ember-ref-modifier ember-ref-bucket主要版本发布后, ember-ref-modifier可能会被弃用 {{ref}}元素修饰符的实现。 受和启发。 安装 ember install ember-ref-modifier 兼容性 Ember...
  • vue3 在v-for中操作dom最佳实践 <template> <div class="rain">... :ref="el => rain[index] = el" :data-set=" 'data' + index" /> <div ref='single'></div> <
  • vue ref介绍

    千次阅读 2020-05-28 15:00:47
    1、ref 加在普通的元素上,用this.ref.name 获取到的是dom元素 2、ref 加在子组件上,用this.ref.name 获取到的是组件实例,可以使用组件的所有方法。 3、如何利用 v-for 和 ref 获取一组数组或者dom 节点      ...
  • Vue教程(ref和$refs的使用)

    万次阅读 多人点赞 2019-08-02 17:55:08
      在Vue中一般很少会用到直接操作DOM,但不可避免有时候需要用到,这时我们可以通过ref和$refs这两个来实现,本文我们就来详细的介绍下这个内容 ref    ref 被用来给元素或子组件注册引用信息, 引用信息将会...
  • VUE3(八)setup与ref函数

    千次阅读 2021-03-01 09:22:15
    2:使用注意点 在 VUE 的模板中使用 ref 的值不需要通过 value 获取 (Vue 会通过自动给 ref 的值加上 .value) 在 js 中使用 ref 的值必须使用 .value 获取 上方代码实现效果: 有好的建议,请在下方输入你的评论...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 804,866
精华内容 321,946
关键字:

ref